Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I want to display the direct category ancestor of a given post. An illustrative example:

These are the categories I have:

  • Cat1
  • Cat2
    • Cat2.1
      • Cat2.1.1
      • Cat2.1.2
    • Cat2.2
      • Cat2.2.1
      • Cat2.2.2.
    • Cat2.3
  • Cat3
  • Cat4

I only put the posts in a single category between a same "level", but when the category has more sub categories, I check the whole trailing, like in:

  • Cat1
  • [X] Cat2
    • [X] Cat2.1
      • Cat2.1.1
      • [X] Cat2.1.2
    • Cat2.2
      • Cat2.2.1
      • Cat2.2.2.
    • Cat2.3
  • Cat3
  • Cat4

Now, in the single post page, I want to display the name of the direct category ancestor of the post (Cat2.1.2 in this case). By default I just use get_the_category(), but it shows the top level category instead (Cat2 in this case). I don't considerer unchecking top levels by now because it cause another problems within the template.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

It is possible that get_the_category() will always return the categories in the correct order (with the deepest at the end), but if it doesn't, you could also loop over all the categories and remove those where another category points to it as their parent.

$post_categories = get_the_category();
$categories_by_id = array();
foreach ( $post_categories as $category ) {
    $categories_by_id[$category->cat_ID] = $category;
}
foreach ( $post_categories as $category ) {
    unset( $categories_by_id[$category->category_parent] );
}
// $categories_by_id will now only contain the deepest categories
share|improve this answer

Well, I guess I found how (not completely tested):

<?php
$category = get_the_category($post->ID);
echo end($category)->cat_name;
?>

Basically, it returns the last category name from the array of categories given by get_the_category.

share|improve this answer
    
Aboslutelly great! Also works with custom taxonomies. –  nacho3d May 25 at 18:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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