Get Top Level Parent Category Id Of a Single Post

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);

See more:


We've 4 Responses

Leave a Reply to M Cancel reply

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this: