You can retrieve the topmost parent category id of a post 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, you can retrieve the parent category id by using

$parent_catid = $cat->category_parent;

Now parent category id will be in the variable $parent_catid

Categorized in: