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

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
LIKE OUR FACEBOOK PAGE

GIVEAWAY

Like & Win
LIKE NOW
* Terms & Conditions Apply
close-link

Join Free Giveaway!

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