Someday before I got a query for getting top parent category of a post.
Query was as following: I have a post, the post is in 3 categories. The category hierarchy is like so:
Fashion
Men
Shoes
Fashion being the “root/top parent” category for the post. I want to display a title at the top of the post which says “Fashion”.
Here I found the code for getting top parent category from the current category or which category you want
Copy and paste below code in function.php file in your wordpress current theme directory:
1 2 3 4 5 6 7 8 9 10 11 | function get_top_parent_cat($cat_ID) { $cat = get_category( $cat_ID ); $new_cat_id = $cat->category_parent; if($new_cat_id != "0") { return (get_top_parent_cat($new_cat_id)); } return $cat_ID; } |
In this function we need to pass the category id as paramter for which we want top parent category.
then call this function where you want.
On category page:
1 2 3 4 | $cat_ID = get_query_var('cat'); $topcat = get_top_parent_cat($cat_ID); echo get_category($topcat); |
On Single post page:
1 | $categories = get_the_category( $post->ID ); |
This will return an array of categories, which you can get the id from, like so:
1 | $categories[0]-> term_id; |
This will be for the first category in the array if there is more than one.
1 2 | $topcat = get_top_parent_cat($categories[0]-> term_id;); echo get_category($topcat); |
So It depends on the location where we want to call the function. But for getting top parent category, we need to call get_top_parent_cat() by passing category id as a parameter.