admin管理员组文章数量:1415636
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;
本文标签: custom taxonomyGet 1st parent category id from post
版权声明:本文标题:custom taxonomy - Get 1st parent category id from post 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745241030a2649330.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论