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?
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?
Share Improve this question edited Dec 3, 2012 at 17:40 dodgerogers asked Dec 3, 2012 at 17:14 dodgerogersdodgerogers 1091 gold badge4 silver badges13 bronze badges1 Answer
Reset to default 1You 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;