2017-05-06 127 views
1

我想這肯定是一個新手問題,但我試圖修改在其他問題上找到的一些代碼,我仍然無法找到如何循環通過類別的職位,並使他們顯示爲Bootstrap 4徽章。通過Wordpress類別與foreach循環

if (! function_exists('mytheme_the_categories')) : 
/** 
* Prints HTML with the categories, formatted as Bootstrap 4 badges. 
*/ 
function mytheme_the_categories() { 
     $categories_list = get_the_category_list(); 
     if ($categories_list && positor_categorized_blog()) { 
      echo '<div class="entry-categories"><span class="sr-only">'. esc_html__('Posted in ', 'positor') . '</span>'; 

      foreach ($categories_list as $category) { 
       echo '<span class="badge badge-primary">'; 
       echo $category->name; 
       echo '</span>'; 

      } 
      echo '</div>'; 
      } 
     } 
endif; 

但是得到一個錯誤: 「警告:的foreach提供了無效的參數()」

回答

0

的解決方案是使用get_the_category()。粘貼下面的工作代碼,以備日後任何人使用Google搜索。

if (! function_exists('mytheme_the_categories')) : 
/** 
* Prints HTML with the categories, formatted as Bootstrap 4 badges. 
*/ 
function mytheme_the_categories() { 
     $categories_list = get_the_category(); 
     if ($categories_list && positor_categorized_blog()) { 
      echo '<div class="entry-categories"><span class="sr-only">'. esc_html__('Posted in ', 'positor') . '</span>'; 

      foreach ($categories_list as $category) { 
       echo '<span class="badge badge-primary mr-1">'; 
       echo $category->name; 
       echo '</span>'; 

      } 
      echo '</div>'; 
      } 
     } 
endif; 
0

你可以通過使用get_categories類別名稱() 代碼是在這裏:

<?php 
      $category_args = array(
       'type'      => 'your_post_type_slug', 
       'child_of'     => 0, 
       'parent'     => 0, 
       'orderby'     => 'id', 
       'order'     => 'ASC', 
       'hide_empty'    => 0, 
       'hierarchical'    => 1, 
       'exclude'     => '', 
       'include'     => '', 
       'number'     => '', 
       'taxonomy'     => 'your_taxonomy_slug', 
       'pad_counts'    => false 

      ); 
      $categories_array = get_categories($category_args); 
      echo '<div class="entry-categories"><span class="sr-only">'. esc_html__('Posted in ', 'positor') . '</span>'; 

      foreach ($categories_array as $categories_val) { 
       echo '<span class="badge badge-primary"><a href="'.get_term_link(intval($categories_val->term_id), $categories_val->taxonomy).'"></span>'.$categories_val->name.'</a>'; 
      } 
     ?>