How to Display Only Child Category in your WordPress Post Loop

Post Category

We have seen this question asked a lot on the WP Forums along with several different answers. It really comes down to what you need. So, we’ll go over how to display the only child category in your WordPress post loop to avoid clutter. A cluttered website is one with too many pages and overly busy design elements. Such sites make it hard to know where to look or what to interact with. In this article, we will try to only show the child category in your WordPress loop.

Unfortunately the_category() does not have any optional parameters like child=0 or depth=-1. While creating WordPress Gallery, this was one of the issues most users have to deal with to organize their single site pages the way they wanted.

To display only Child Category in your wordpress post loop (mostly single.php), all you need 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 alternate the quantity 10 to your guardian class’s ID.

In our gallery’s case, we had the parent category called Framework, and a group 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 flawlessly.

We hope this article helps you How to Display Only Child Category in your WordPress Post Loop.  If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

About This Author

0 Comments

You can post comments in this post.

Post A Reply