2016-04-21 140 views
1

这似乎很简单,但我不知道为什么下面的代码不起作用。我在谷歌全面搜索,有很多解决方案,但不为我工作。伙计们,请让我知道我错过了什么。在Wordpress中显示帖子的类别和子类别列表

我下面的代码:

这只是给我的类别而不是子类在其中。 请帮助任何人。

在此先感谢。

+0

为什么不使用['wp_list_categories()'](https://developer.wordpress.org/reference/functions/wp_list_categories/)? – MinhTri

+0

我也尝试过,但得到同样的东西.. :( –

+0

禁用所有插件,然后尝试核心WordPress主题。确保子类别存在。 – MinhTri

回答

0

嘿,我找到了解决办法:

<ul class="category-sidebar"> 
     <?php 
     $get_parent_cats = array(
     'parent' => '0','hide_empty' => false //get top level categories only 
     ); 

     $all_categories = get_categories($get_parent_cats);//get parent categories 

     foreach($all_categories as $single_category){ 
     //for each category, get the ID 
     $catID = $single_category->cat_ID; 

     echo '<li><a href=" ' . get_category_link($catID) . ' ">' . $single_category->name . '</a>'; //category name & link 
     $get_children_cats = array(
     'child_of' => $catID,'hide_empty' => false //get children of this parent using the catID variable from earlier 
     ); 

     $categories = get_categories($args); 

     $child_cats = get_categories($get_children_cats);//get children of parent category 
     echo '<ul class="children">'; 
     foreach($child_cats as $child_cat){ 
     //for each child category, get the ID 
     $childID = $child_cat->cat_ID; 

     //for each child category, give us the link and name 
     echo '<a href=" ' . get_category_link($childID) . ' ">' . $child_cat->name . '</a>'; 

     } 
     echo '</ul></li>'; 
     } //end of categories logic ?> 
     </ul> 

谢谢大家对你的时间。 :)