Show wordpress subcategories only

2019-02-07 15:48发布

问题:

I have 7 Categories (parents), and every category has 15 sub-categories.

When I select some category (parent), I want to display only sub-categories (children) of that particular parent category (parent).

After I click on sub-category (child) then it should display its posts only.

I have a fron_page.php and category.php.

How can I write this to first show sub-categories separately, then post of that sub-category separately in new file, which user want to see.

回答1:

This code should help you:

<ul> 
<?php 
 $cats = get_the_category();
 $mycat = $cats->cat_ID;
    wp_list_categories('orderby=id&child_of='.$mycat); 
?>
</ul>

OR

<?php
if (is_category()) {
    $cat = get_query_var('cat');
    $this_category = get_category($cat);
    $this_category = wp_list_categories('hide_empty=0&hierarchical=true&orderby=id&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");
    if($this_category !='<li>No categories</li>')
    {
     echo '<ul>'.$this_category.'</ul>'; 
    }
}
?>

Let me know please.

Good luck! :)



回答2:

1) Showing only Subcategories:

<?php
    // if the page visitor views is a category page
if (is_category())
{
$cur_cat = get_query_var('cat');
    if ($cur_cat) 
    {
        $new_cats = wp_list_categories('echo=false&child_of=' . $cur_cat . '&depth=1&title_li=&&show_count=1&hide_empty=0');
        echo '<ul>' . $new_cats . '</ul>';
    }
}
?>

2) Showing All Top Categories:

<?php 
wp_list_categories('depth=1&title_li=&exclude=1&show_count=1&hide_empty=0');
?> 

3) Showing All Top Categories + Subcategories like a Tree menu:

Use plugin, called FoCal

4) view this topic

http://wpworks.wordpress.com/2011/01/13/displaying-categories-and-subcategories-tree-on-wordpress/