In our previous post, we sharedΒ how you can only display parent category in your WordPress Post Loop. This article is the continuation of the similar technique except here we will try to only show child category in your WordPress loop. UnfortunatelyΒ the_category()Β does not have any optional parameters like child=0 or depth=-1. When creating ourΒ WordPress Gallery, this was one of the issues we had to deal with to organize our single site pages the way we wanted.
To display only Child Category in the post loop (mostly single.php), all you have to do is replace the following code:
with this code:
foreach((get_the_category()) as $childcat) {
if (cat_is_ancestor_of(10, $childcat)) {
echo ‘<a href=”‘.get_category_link($childcat->cat_ID).'”>’;
Β echo $childcat->cat_name . ‘</a>’;
}}
?>
Remember to change the number 10 to your parent categoryβs ID.
In our galleryβs case, we had the parent category called Theme Framework, and bunch of child categories. Each post was only going to be assigned one child category for the framework (for example Genesis). So this code worked out perfectly. See the live example by clicking the image below:
Hope this trick solves your problem as well.
Reference:
WordPress Codex