Wordpress – Function to get parent category id

Parent Category id of a post can be retrieved by using the following function

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

Place the above code in function.php in your theme folder or place in the function.php in wp-include folder (to use the function in any theme).

From any of the page simply call the function an get the parent category id in a variable, like this

$parent_catid = get_posts_parent_category_id();

Now you have the parent category id in $parent_catid variable

Leave a Comment