Wordpress function to get the top-level category of a message?

Hi, I am trying to find the largest category of message. I tried to find any WP built-in functions, but could not.

For example, I have such categories.

Parent sub-1 sub-2 

And I have a post in sub-2. So, with the identifier sub-2, I am trying to find the identifier of the topmost category called "Parent" in this example.

+4
source share
7 answers

Well, I ended up creating my own function to get the top category of the highest level.

 // 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; } 
+12
source

Take a look at this useful script: Get the parent ID of the top level of a single post

And you can change this part:

 $catParent = $cat->cat_ID; 

to

 $catParent = $cat->name; 

To get the name of a top-level category

+1
source

For those who have problems with this method, I found a simple solution, perhaps not the best in terms of efficiency. To get the parent top level category on the post / product page

Using:

 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); 

Functions:

 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; } 
0
source

try it

 $categories = get_categories( array( 'orderby' => 'name', 'parent' => 0 //this parameter is important for top level category ) ); 
0
source

Good answer today:

 $cats = get_the_terms( false, 'category' ); $topcat = array(); foreach($cats as $cat) { if ($cat->parent == 0) $topcat = $cat; } 

Because get_the_category will not return the category "sub1" if the message is only in "sub2", even if "sub2" is a subcategory of "sub1". And you can get the cat id with get_cat_ID ...

0
source
  $top_category = get_the_category_list(','); echo $top_category; 
0
source

I need a parent id and this worked well and just for me:

 $topcat = get_the_category(); echo $topcat[0]->category_parent; 
-2
source

Source: https://habr.com/ru/post/1390481/


All Articles