Wordpress widget how to only display sub-categorie

2020-02-26 11:33发布

I was wondering if anybody know hows to modify the existing category widget to only display the categories within the selected parent category. Example:

If my categories are structured like:

  • Computers
    • Laptops
    • Desktops
    • Software
  • Electronics
    • Cameras
    • Audio/Video

If somebody is viewing posts in the Computers category I would like the categories widget in the side bar to only display Laptops, Desktops & Software..

Is there a way to get this done? Is anybody familiar of a plugin that maybe do that? Thanks!

3条回答
冷血范
2楼-- · 2020-02-26 12:14

1) To Show only Subcategories:

<?php
    // check if the page is viewed 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) To Show All Main Categories:

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

3) To show All Categories + Subcategories like Tree menu:

Use FoCal plugin. 

4) view this code too:

http://wpworks.wordpress.com/2011/01/13/displaying-categories-and-subcategories-tree-on-wordpress/
查看更多
一夜七次
3楼-- · 2020-02-26 12:21

Thanks for your help. I was able to get it to work by doing this...

<?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 '<h3>Products</h3>'; 
     echo '<ul>'.$this_category.'</ul>'; 
    }
}
?>
查看更多
在下西门庆
4楼-- · 2020-02-26 12:28

how about using something like this? on a singles page you could add a call from within the single.php page to a new sidebar or an include file...?

ie:

<?php if( is_single() ) { include(TEMPLATEPATH.'/newsidebar.php'); } ?>

newsidebar.php

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

this will show only categories from the currently used category?

ie:

if current category is 5 // Computers then all that will be shown in the list is

* Laptops
* Desktops
* Software
查看更多
登录 后发表回答