Get Parent Category ID of Current Category

Get the parent category ID from the current category ID in WordPress. The Function will return the Parent Category ID.

1. Include the function in your function.php page.

function get_categories_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
  $catParent = $cat->cat_ID;
 }

2. Call the function from the page in which you want the parent category id.

$cur_cat_id = get_query_var('cat');
$parent_catid = get_categories_parent_id( $cur_cat_id );

Here $cur_cat_id contains the category id which id obtained from the function get_query_var(‘cat’), which is called in the category.php page to obtain current category id.

If you are using the function in any other page in which you know the current category id, simply assign the value to $cur_cat_id, to obtain its parent category ID.

Now after calling the function get_categories_parent_id( $cur_cat_id ), you will have the parent category ID in $parent_catid.

Leave a Comment