Get the top level parent category ID of the single post being viewed on single.php. Works on single.php.
Step 1
Requires this function. Place it in your functions.php or other function file.
/** * Returns ID of top-level parent category, or current category if you are viewing a top-level * * @param string $catid Category ID to be checked * @return string $catParent ID of top-level parent category */ function smart_category_top_parent_id ($catid) { while ($catid) { $cat = get_category($catid); // get the object for the catid $catid = $cat->category_parent; // assign parent ID (if exists) to $catid // the while loop will continue whilst there is a $catid // when there is no longer a parent $catid will be NULL so we can assign our $catParent $catParent = $cat->cat_ID; } return $catParent; }
Step 2 – Usage
Use this in single.php to get the category id of the top level parent category.
// get the top level cat id of a single post $category = get_the_category($post->ID); $catid = $category[0]->cat_ID; $top_level_cat = smart_category_top_parent_id ($catid);
Aryane Floriano
January 30th, 2014 at 12:36 pm
Thank you so much!
M
February 3rd, 2016 at 5:46 am
Awesome! 🙂
dot net
November 28th, 2018 at 3:51 am
Great………..
de Laage
August 18th, 2020 at 10:14 am
Thank you so much. It helped me a lot