2017-05-08 64 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); 
    } 
} 
?>