0

I have this structure for my categories:

Issue 4
       - News
           - Supporting our troops
           - Breaking news

<?php
$category = get_the_category();
$parent = $category[0]->term_id;
?>

This code gets the top level category ID from "Breaking News" which is Issue 4, missing out News its direct parent category.

How could I get the category ID for "News", its direct parent category and not the top level category?

1 Answer 1

1

You need to use get_ancestors().

Assuming your post is only in one category, the following code should work (if it's in multiple you'll need to loop through each of the assigned categories to determine the various hierarchies).

$category = get_the_category();
$ancestors = get_ancestors( $category[0]->term_id, 'category' );
$direct_parent_id = $ancestors[0];

If you want to get the entire category hierarchy as an ordered array of IDs (which I like to have available) you'd do:

$category = get_the_category();
$hierarchy = array_reverse( get_ancestors( $category[0]->term_id, 'category' ) );
$hierarchy[] = $category[0]->term_id;
4
  • Hi ggutenburg, this is great thanks, Im slightly puzzled by one thing though. Using the array of ID's and viewing the second entry via heirachy[1] sometimes shows that a post has no 2nd level parent category, which isnt the case. Every post belongs to a top level category ( an issue) and then a sub category. Do you know why this may be the case? Dec 3, 2012 at 18:17
  • get_ancestors() only gives you the parents (and grand-parents, etc.), not the assigned category. That's why in the 2nd example I append $category[0]->term_id to the $hierarchy array. Does that answer your question?
    – ggutenberg
    Dec 3, 2012 at 18:21
  • Also, if you assign the post to 2 categories (rather than just the last category in the hierarchy), you'll need to add some looping logic as $category[0] will only be one of the assigned categories, and if it's the top level category it will have no ancestors.
    – ggutenberg
    Dec 3, 2012 at 18:33
  • I think it does, I think theres an issue with some of my categories which for some reason aren't being registered under the correct heirachy.So Issue 4 -> News -> Some news is becoming Issue 4 -> Some news. Dec 3, 2012 at 18:35

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.