WordPress – Get Parent Category ID

The top most parent category id of a post can be retrieved by using this three line code.

$category = get_the_category();
$cat = get_category($category[0]->term_id);
$parent_catid = $cat->category_parent;

The first line will get the category of the current post.

The second line will create an object of the first category of the post.

Here the id of the first category can be get by using the code $category[0]->term_id

Finally the parent category id can be retrived by using

$parent_catid = $cat->category_parent;

Now parent category id will be in the variable $parent_catid

Sharing is caring!

Leave a Comment

DON’T MISS OUR GIVEAWAYS!
Subscribe To Newsletter
Subscribe to our newsletter and get all the latest updates offers and giveaways right in your inbox.
Subscribe
Give it a try, you can unsubscribe anytime.
close-link

Join Free Giveaway!

Subscribe to our newsletter to get latest offers and giveaways!
SUBSCRIBE
close-link