Get parent category from child in WordPress

Hello friends!
Happy to write amongst the overloaded work. In this post you will find a simple PHP snippets that fetches a Parent Category name using a Child Category in WordPress. I’m not promising the authenticity of the code because the World is big enough to have a lots of idea. This WordPress snippet was derived to meet a one of client’s need. The reason in posting this snippet is that i did not find few lines of code or chunk of code which i was searching for.

Briefing about my theme & reason for this code’s necessity
I used this code in ‘archive.php’ which is navigated through ‘category.php’ of a WordPress theme. Let me explain the structure of the theme i worked. The primary menu is comprised of categories and their sub-categories. The posts have been tagged only under the child categories and not the parent ones. Hence, when the visitor clicks on the parent category the category page will display the description of the parent category and list out the child category. Now, retrieving parent and child categories at this points can be done hands down. (refer the below image).

wordpress parent category

The real issue
As the sub-category page of a parent is clicked, WordPress takes us to the ‘archive.php’ page (if you don’t have ‘category.php’, i didn’t have) to display further information like in the above image sidebar containing the parent category and hierarchically displaying its child. Remember, that we are in-depth of level 2, this is where i found myself paused while retrieving the parent category name.

After crawling numerous pages i had to bite the necessary chunks from all the available code snippets so that i could complete this task. Finally, the below is the code i derived by filtering the codes i bit from other pages and here it is…

Code briefing
The above code chunk retrieves the parent category ID and its name. This is done as the below steps:

  1. get the resultant array of get_category()
  2. matching the current category id (of child) with one within the resultant category array
  3. when both the category matches, we find its parent from the array key of ‘parent’
  4. since we have the parent ID, now its easy to get its children using the second chunk of code and list them out.


This code can be used in the category.php and get the parent and its corresponding child category dynamically without any hindrances. I would like you to use the code in your project and let me know if you find it difficult or error, so that I get the chance of correcting the code and update here.

Thanks for reading this post 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.