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!

Related Posts

Leave a Comment

shares