Displaying a posts current category and parent category only

Since WordPress doesn’t allow for limiting the category in “the_category” I had to write some custom code to achieve limiting the categories displayed for the current post to the current category and it’s parent.

<?php //display the current and parent category (2 total)
$category = get_the_category();
$current_category = $category[0];
$parent_category = $current_category->category_parent;
if ( $parent_category != 0 ) {
echo '<a href="' . get_category_link($parent_category) . '">' . get_cat_name($parent_category) . '</a>';
}
echo '<a href="' . get_category_link($current_category) . '">' . $current_category->cat_name . '</a>';
?>

props: Nick

About the Author, Dan Cameron:

I'm the owner and solution engineer at Sprout Venture, a web solutions company that specializes in web development including WordPress.

I started my first blog in 2003 and transitioned to WordPress in 2004. Since moving to WordPress I've written a few plugins and themes for public consumption. Lately I'm busy engineering/building/coding and have only been able to share a few code snippets.

If you're in need of some web development, web design or custom WordPress plugins and/or themes contact me, I'll be happy to discuss it with you.

Read More »

  • Andrew
    Wondering if you can help...
    I have 3 categories - one, two and three
    On each category page, i want to display the post, plus a link to all the subcategories of "three" that the post is assigned to. I can't seem to do this cause like you said, there is no limit ability that i can find :(
  • I don't understand. Do you want to show the subcategories of the current post only?
  • Thanks. You did help...which I totally forgot.
  • Nice code ;)
blog comments powered by Disqus