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

1. Include the Function on 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 on 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 where you know the current category id, 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.

Categorized in: