(+84) 463.28.7979

Display Subcategories on Category Pages in WordPress


When using WordPress as a CMS, or even as a blog you might want to display subcategories on category pages. There is really no easy way to do this and some ways that are out there on the web has various bugs. In this article we will show you how you can display subcategories on category pages using this hack.

Now the hack shared on Yoast’s blog is outdated and has bugs. The bug is that even though it shows the subcategories on the category page, but when you go inside the subcategory, it does not show any category. With the hack we are sharing it will show subcategories on the parent category pages, and when you click on the subcategories, you will still see other sibling categories in the parent category.

Ok if the above terminology did not make sense to you let us explain in another way. Lets say you have a top level (parent) category called Sports. You have three subcategories under sports called NFL, NBA, and MLB. Now when someone arrive to your homepage, you will only see Sports category and other top level parent categories. When someone clicks on Sports, the categories will now show only the subcategories under Sports, so it will be NFL, NBA, and MLB. Now with Yoast’s hack if you click on NFL, everything will be gone. With our hack when you click on NFL, it will still show NFL, NBA, and MLB.

So basically this hack is allowing you to List subcategories if viewing a Category, and brothers / sibling categories if in subcategory.

<?php
if (is_category()) {
$this_category = get_category($cat);
}
?>
<?php
if($this_category->category_parent)
$this_category = wp_list_categories(‘orderby=id&show_count=0
&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&show_count=0
&title_li=&use_desc_for_title=1&child_of=’.$this_category->cat_ID.
“&echo=0″);
if ($this_category) { ?>

Paste the above code wherever you like the categories to display and modify it however you please. The code listed above, when you visit the subcategory from the main category, hides the main category and only shows the subcategories.

If you want to show the main category also on subcategory pages, just remove the parameter depth=”1″ from the code above.

This is a very useful and handy category hack when it comes to designing templates for WordPress specially when using WordPress as a CMS.

For further details on parameters refer to WordPress Codex.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>