最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

custom taxonomy - Get 1st parent category id from post

programmeradmin2浏览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?

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 badges
Add a comment  | 

1 Answer 1

Reset to default 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;
发布评论

评论列表(0)

  1. 暂无评论