WordPress: Display Child Category

Posted July 21, 2011

For my new WordPress theme, I wanted to display the child category for my portfolio projects. I have placed all my objects within main categories(such as Blog and Portfolio) and given them more specific categories for description within the parent. When doing a loop to display my latest portfolio posts, I wanted to display the category(ies), but since the heading for the section is entitled “Latest Projects”, it would be redundant to show that the items are categorized within ‘Portfolio’.

The WordPress function to display the catagory of a post is

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

This will display all the categories, parent and children. To get the child, we have to load a string with the child after checking if there is in fact a child category.

<?php

     foreach((get_the_category()) as $childcat) {
     if (cat_is_ancestor_of(11, $childcat)) {
     echo $childcat->cat_name;
     }}
?>

 

Leave a Reply

Permitted HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>