I wanted to show the subcategories for a given category on it’s category page in the sidebar, but somehow the code for this wasn’t readily available. Basically you need to check whether there are any children, and if there are, list the categories with the current category as a parent or grandparent. The following code does just that:
[sourcecode language="php"]
if (is_category()) {
$this_category = get_category($cat);
if (get_category_children($this_category->cat_ID) != “”) {
echo ”
Subcategories
“;
echo ”
“;
wp_list_categories(’orderby=id&show_count=0&title_li=
&use_desc_for_title=1&child_of=’.$this_category->cat_ID);
echo ”
“;
}
}
[/sourcecode]
Have fun with it!
Showing subcategories “dynamically”
This piece of code is actually a response on a query on the Czech WordPress support forum, where a guy asked how to display a list of categories that are children of the just active (browsed) one. I didn’t have a clue, although I thought this could be a very common request: on many pages you can see the category navigation that after the activation of one particular item gets more concrete, to put it differently, the subcategories are shown as an offer while browsing a category.
<?php
// outputs usual category-list
wp_list_categories('title_li=<h2>Categories</h2>');
// outputs subcategories in same way, if there are any (if you're browsing a parental category)
$has_children = (bool)(get_category_children(intval(get_query_var('cat'))));
if (is_category() AND $has_children) {
wp_list_categories('title_li=<h2>Subcategories</h2>&child_of=' . intval(get_query_var('cat')));
}
?>
For more comfortable testing I recommend to add hide_empty=0 paramater and perhaps $has_children variable needs an explaining note: It’s here because a try to output the list of subcategories can end with an visible error, if there are found no subcategories (= if you would try to show subcategories of a category having not a one children
).

RSS Feeds
Feed Comment 




Leave Your Comments Below