When using WordPress as a CMS, or even a blog, you may want to display subcategories on category pages. There really isn't an easy way to do this and some of the ways that exist on the web have various bugs. In this article, we will show you how you can display subcategories on category pages using this trick.
Now the hack shared on the Yoast blog is outdated and buggy. The bug is that even though it shows the subcategories on the category page, but when you go inside the subcategory, it doesn't show any category. With the trick we are sharing, it will display the subcategories on the main category pages and when you click on the subcategories, you will still see other sibling categories in the main category.
Okay, if the above terminology didn't make sense to you, let us explain it another way. Let's say you have a top level (parent) category called Sports. You have three subcategories in sports called NFL, NBA, and MLB. Now when someone lands on your home page, they will only see the Sports category and other top level main categories. When someone clicks on Sports, the categories will now show only the subcategories under Sports, so those will be NFL, NBA, and MLB. Now with the Yoast hack, if you click on NFL, everything will be gone. With our trick clicking on NFL will still show NFL, NBA and MLB.
Basically, this trick allows you to list subcategories if you're viewing a category, and brother/sister categories if in a subcategory.
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 where you want the categories to display and modify it as you like. The code listed above, when you visit the subcategory of the main category, hides the main category and only shows the subcategories.
If you want to display the main category also on the subcategory pages, just remove the depth="1" parameter from the code above.
This is a very useful and useful trick when it comes to designing templates for WordPress, especially when using WordPress as a CMS.
For more details on parameters, please refer to the WordPress Codex.