0

I have a blog which has three top level categories. Each top level category has a list of sub categories. I am displaying only certain top level category posts in certain sections of the website.

When viewing the post I want to display something like: Posted under Cards, Races, Lifestyle

These three categories would be children of a top leve category. How could I list these categories and exclude the top level category when listing how a post is categorized? Thanks.

2 Answers 2

1

Here's a function that get's the category from the post and then displays an unordered list of term children links. I'm assuming you only have one category per post. If you don't, then you'd have to iterate through $cat_id in addition to $cat_children:

// get category id
$cat_id = get_the_category();
// get array of all children of the first category assigned to the post
$cat_children = get_term_children( $cat_id[0]->term_id, 'category' );
// start building our list
$cat_children_list = '<ul>';
foreach( $cat_children as $child ) {
    // get the term object of each child term
    $term = get_term( $child, 'category' );
    // output the list item with link and label
    $cat_children_list .= '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a><?li>';
}
// finish up the list
$cat_children_list .= '</ul>';
// echo the output
echo $cat_children_list;
1

While inside of the loop you can use the_category().

The second parameter of the_category() can be an empty string which will put out a link to the child category and not show the relationship to the parent.

2
  • That's not quite working. I am using: <?php the_category(', '); ?> and tried using: <?php the_category(', ', ''); ?> both will output all the categories, including the top level categoy (which is the one I want to exclude).
    – Robbie
    Commented Jul 25, 2012 at 13:59
  • I am going to assume that the posts are also categorized with the top level category. Maybe they shouldn't be. Try only selecting the child categories.
    – nvwd
    Commented Jul 25, 2012 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.