2017-05-08 80 views
0

我使用下面的代码输出自定义分类的列表:添加HTML到PHP循环

<?php // Get terms for post 
    $terms = get_the_terms($post->ID , 'status'); 
    // Loop over each item since it's an array 
    if ($terms != null){ 
     foreach($terms as $term) { 
      // Print the name method from $term which is an OBJECT 
      print $term->slug ; 
      print $term->name; 
      // Get rid of the other data stored in the object, since it's not needed 
      unset($term); 
     } 
    } 
?> 

我的问题是,我怎么可以添加HTML这个循环?我已经尝试了多种方法,例如:

echo '<button class="filter $term->slug" data-filter="$term->slug">$term->name</button>'; 

...但是,这可能会出错或不打印所需的条款。我希望的HTML输出将是:

<button class="filter term-slug" data-filter="term-slug">term-name</button> 

在此先感谢。

+0

回应应该工作。你能举一个例子说明你如何使用echo来做到这一点? – Jerodev

+0

@jerodev感谢您的评论。我已经更新了我的答案。它输出html并将这些项输出为静态文本,但不会对它们进行操作。 – CharlyAnderson

回答

0

请试试这个方法。它应该工作。您需要在HTML中像这样打印'".$term->name."'以标识对象变量。

<?php // Get terms for post 
     $terms = get_the_terms($post->ID , 'status'); 
     // Loop over each item since it's an array 
     if ($terms != null){ 
      foreach($terms as $term) { 
       // Print the name method from $term which is an OBJECT 



      echo '<button class="filter "'.$term->slug.'"" data-filter="'.$term->slug.'">'".$term->name."'</button>'; 

       // Get rid of the other data stored in the object, since it's not needed 
       unset($term); 
      } 
     } 
    ?> 
+0

请修复您的报价。 –

+0

@u_mulder,我修复了我的引号。谢谢。 –

+0

谢谢你的帮助:-) – CharlyAnderson

0

重写你的线路如下: -

echo "<button class='filter {$term->slug}' data-filter='{$term->slug}'>$term->name</button>"; 
0

请添加以下代码和检查。

<?php 
$terms = get_the_terms($post->ID , 'status'); 
if ($terms != null) 
{ 
    foreach($terms as $term) 
    { 
     echo '<button class="filter "'.$term->slug.'"" data-filter="'.$term->slug.'">'".$term->name."'</button>'; 
     unset($term); 
    } 
} 
?>