1

I have a product page which is assigned as category.php. Now i want to show Sub Categories as Sub Menu on the Category page. But even after searching alot i couldn't show all sub categories yet. I found one code which is :

 <?php
if (is_category()) {
$this_category = get_category($cat);
}
?>
<?php
if($this_category->category_parent)
$this_category = wp_list_categories('orderby=id
&title_li=&use_desc_for_title=1&child_of='.$this_category->category_parent.
"&echo=0"); else
$this_category = wp_list_categories('orderby=id&depth=1
&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID.
"&echo=0");
if ($this_category) { ?> 

<ul>
<?php echo $this_category; ?>

</ul>

<?php } ?>

but what this is doing is it doesnt shows up the sub categories which has 0 posts. Also it shows NO CATEGORIES where categories don't have any sub categories and There is a bullet before every listing, which i dont want at all. So Please help.

1
  • You will need to use css to hide the bullets. And try setting hide_empty=false to show sub categories with 0 posts
    – ngearing
    Sep 8, 2016 at 6:09

1 Answer 1

3

You can use get_categories & wp_list_categories with specific parameters (to use directly in you category.php template):


// List sub cats
$params = array(
    'parent'        =>  get_queried_object_id(), //id of current category displayed 
    'orderby'       => 'name',
    'order'         => 'ASC',
    'hide_empty'    =>  false // do not hide sub cats without posts
);
if ( count( get_categories( $params ) ) ) {
    wp_list_categories( $params );
}

Full list of arguments can be found here

You can also customize the output by user your own Walker extending WP's Walker_Category class.

2
  • I have used wp_list_categories but in my case it wouldn't be the correct way to show categories as it lists all the category with <li> tag, so Sep 12, 2016 at 12:52
  • 1
    It's not an issue as you can use the 'walker' argument in wp_list_categories and assign it a custom 'Category walker' : developer.wordpress.org/reference/classes/walker_category Just create a "My_Walker_Category" (or whatever) that extends Wordpress "Walker_Category". Then you just have to customize the rendering process in you custom walker class by overwritting the methods start_lvl, end_lvl, start_el, end_el.
    – Dexter0015
    Sep 15, 2016 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.