WordPress: Get ID of top-level parent category

I wanted to get the ID of the top level parent category of the current category such that, if the current category was a child of a child category (or any number levels down), I would have the top-level category ID returned to me. This post showing how to get the parent category ID sent me in the right direction and I’ve developed it a bit to fulfil my requirements.

It was also important that if I was browsing a top-level parent category, then I would just get the current category ID. The following function does the work in a nice simple fashion. All you need to do is feed it the current category ID.

The Function

* 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 pa_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;


Obviously this function can be used in a variety of locations, but if you were checking things in your category.php template file you would use it as follows. In the case below I’m just echoing the top-level parent category ID.

$catid = get_query_var('cat');
echo pa_category_top_parent_id ($catid);

I hope someone finds this useful!