Get parent category from child in WordPress: Method 2

In the earlier post I had explained the code to retrieve parent category from the child category. Similarly the code snippet below does the same but it retrieves its root parent category irrespective of the depth of the child category.
fetch wordpress parent category

The Code

What it does

Starting at line no.7, we are checking for the category page. This is optional. Proceeding, we retrieve the current category attributes to access through an object ($cat_obj). Then, using this category object we fetch the Id of the current category and passing the category object to our custom-made function called ‘get_root_category()’. This function eliminates the process of iteration.

Within the function we iterate the category object to get the root parent for the current category. Suppose, the depth is

category 1
|- category 1.1
|– category 1.1.4
|— category (current position).

The output of the function will be ‘category 1’.

This root category is retrieved by the while loop searching for category parent Id which is ‘0’ with the help of category object. Thus we succeed in retrieving the root category of the current category.

Hope, this will help and request you to use them and report on error (if any)!

Thanks for reading and as usual, I’m open to suggestion and critics (positive of course).
Do comment on! And if possible do contribute.


Post Author: Shreyo

is a developer & involved in project management; loves to learn, guide and keep himself updated on UI/UX and WordPress. He is also an amateur photographer mostly macro shots.