Getting top parent category

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:

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:

On Single post page:

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.

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.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.