categories - Get top parent category

My category structure is as follows:- Top Category---- Sub Category 1------- Sub Sub Category 1.1------- Sub Sub Cate

My category structure is as follows:

- Top Category
---- Sub Category 1
------- Sub Sub Category 1.1
------- Sub Sub Category 1.2
------- Sub Sub Category 1.3
---- Sub Category 2
------- Sub Sub Category 2.1
------- Sub Sub Category 2.2
------- Sub Sub Category 2.3

I'm on a post under 1.2 so it would be:

Top Category -> Sub Category 1 -> Sub Sub Category 1.2 -> Current Post

NB: In the post ONLY "Sub Category 1" and "Sub Sub Category 1.2" are selected as categories ("Top Category" is not checked).

Now, how do I get get the slug of the Top Category ("top-category"), navigating backward?

Thanks!

My category structure is as follows:

- Top Category
---- Sub Category 1
------- Sub Sub Category 1.1
------- Sub Sub Category 1.2
------- Sub Sub Category 1.3
---- Sub Category 2
------- Sub Sub Category 2.1
------- Sub Sub Category 2.2
------- Sub Sub Category 2.3

I'm on a post under 1.2 so it would be:

Top Category -> Sub Category 1 -> Sub Sub Category 1.2 -> Current Post

NB: In the post ONLY "Sub Category 1" and "Sub Sub Category 1.2" are selected as categories ("Top Category" is not checked).

Now, how do I get get the slug of the Top Category ("top-category"), navigating backward?

Thanks!

Share Improve this question edited Apr 25, 2015 at 12:59 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Apr 25, 2015 at 12:23 medkmedk 1511 gold badge1 silver badge3 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 4

get_ancestors() returns an array containing the parents of any given object.

This example has two categories. The parent with the id of 447 and the child with a id of 448 and returns the a category hierarchy (with IDs):

get_ancestors( 448, 'category' ); 

returns:

Array
(
    [0] => 447
) 

get_ancestors Codex Page

get_ancestors()

Is the correct way to get all the parent categories of a specific category in the hierarchical order, so to get the highest level parent you could extract the last item of the array returned like this:

// getting all the ancestors of the categories 
$ancestor_cat_ids = get_ancestors( $queried_cat_id, 'category');

// getting the last item of the array of ids returned by the get_ancestors() function
$highest_ancestor = $ancestor_cat_ids[count($ancestor_cat_ids) - 1];

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745144028a4613563.html

相关推荐

  • categories - Get top parent category

    My category structure is as follows:- Top Category---- Sub Category 1------- Sub Sub Category 1.1------- Sub Sub Cate

    10小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信