How to Display Only Child Category in your WordPress Post Loop

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:

<?php the_category(', '); ?>

with this code:

<?php
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:

Display Only Parent Category in Your WordPress Loop

Hope this trick solves your problem as well.

Reference:

WordPress Codex