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 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:
$cat = get_category( $cat_ID );
$new_cat_id = $cat->category_parent;
if($new_cat_id != "0")
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:
$cat_ID = get_query_var('cat');
$topcat = get_top_parent_cat($cat_ID);
On Single post page:
$categories = get_the_category( $post->ID );
This will return an array of categories, which you can get the id from, like so:
This will be for the first category in the array if there is more than one.
$topcat = get_top_parent_cat($categories-> term_id;);
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.