Wordpress function to get top level category of a

2019-06-26 03:10发布

Hi I am trying to find the top most category of a post. I tried finding any WP builtin functions but failed.

For example I have categories like this.

Parent
     sub-1
          sub-2

And I have a post in sub-2. So with the ID of sub-2, I am trying to find the ID of top most category which is named "Parent" in this example.

标签: wordpress
6条回答
对你真心纯属浪费
2楼-- · 2019-06-26 03:33

Look at this helpful script: Get Top Level Parent Category Id Of a Single Post

And you can change this part:

$catParent = $cat->cat_ID;

To

$catParent = $cat->name;

To get the name of the top level category

查看更多
唯我独甜
3楼-- · 2019-06-26 03:36

I needed parent ID and this worked nice and simple for me:

$topcat = get_the_category();
echo $topcat[0]->category_parent;
查看更多
唯我独甜
4楼-- · 2019-06-26 03:38

Ok I ended up building my own function to get the top most level category.

// function to get the top level category object
// Usage - $top_cat = get_top_category();
// echo $top_cat->slug;

function get_top_category() {
    $cats = get_the_category(); // category object
    $top_cat_obj = array();

    foreach($cats as $cat) {
        if ($cat->parent == 0) {
            $top_cat_obj[] = $cat;  
        }
    }
    $top_cat_obj = $top_cat_obj[0];
    return $top_cat_obj;
}
查看更多
我只想做你的唯一
5楼-- · 2019-06-26 03:45

For the ones having problems with this method I found a simple solution, probably not the best one in terms of efficiency. To get the top level category parent from post/product page

Usage:

global $post;
$terms = wc_get_product_terms( $post->ID, 'product_cat', array( 'orderby' => 'parent', 'order' => 'DESC' ) );
if ( ! empty( $terms ) ) {
    $main_term = $terms[0];
    $root_cat_id = get_top_category($main_term->term_id);

Function:

function get_top_category ($catid) {
$cat_parent_id=0;
while ($catid!=null & $catid!=0) {
    $current_term = get_term($catid); 
    $catid = $current_term->parent; 
    if($catid!=null & $catid!=0){
        $cat_parent_id = $catid;
    }else{
        $cat_parent_id = $current_term->term_id;
    }
}
return $cat_parent_id;
}
查看更多
趁早两清
6楼-- · 2019-06-26 03:48

The good answer today is:

$cats = get_the_terms( false, 'category' );
$topcat = array();

foreach($cats as $cat)
{
    if ($cat->parent == 0)
        $topcat = $cat;  
}

Because get_the_category wont return "sub1" category if the post is just in "sub2", even if "sub2" is a sub category of "sub1". And you can get the cat ID with get_cat_ID...

查看更多
我想做一个坏孩纸
7楼-- · 2019-06-26 03:50

try this

$categories = get_categories( array(
    'orderby' => 'name',
    'parent'  => 0 //this parameter is important for top level category
    )
);
查看更多
登录 后发表回答