Get ID of parent category

The problem

Sometimes you need to get the ID of the parent category when you’re browsing a child category page. Don’t you? :)

The solution

Get the ID of the parent category with a few lines of PHP code:

<?php
if( is_category() ) {
  $q_cat = get_query_var('cat');
  $cat = get_category( $q_cat );
  echo $cat->category_parent; // Print the ID
}
?>

Requirements

  • WordPress 1.5.1 and above

Tags: , , ,

11 comments

  1. [New Blog Post] Get ID of parent category http://bit.ly/470wHg
    #wp

  2. Great little snippet for getting the parent ID in WP http://bit.ly/gFoxsZ

  3. Thank you SO VERY MUCH!!!!

  4. Been looking for this for a good bit, thanks.

  5. Thanks You very very much.

  6. [...] 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 [...]

  7. Well, sometimes you waste hours searching for something you exactly need and find nothing and sometimes you are bang on target. I was looking getting subcategory ids too so i wrote this under your function

    // get the sub category if we have them
    foreach ($categories as $cat) {
    $parent = $cat->category_parent;
    if ($parent != 0 ){
    $sub_cat_ID = $cat->cat_ID;
    $sub_cat_name = $cat->cat_name;
    $sub_cat_url = get_category_link($sub_cat_ID);
    }
    }

    Now, i have category and subcategory id’s both.

  8. Very useful thank you! I also needed to check if the category was a sub category for displaying a different layout. I only have one level of subcategories that I was checking against so I added:

    if($parent_cat != 0){
    echo “This is a subcategory”;
    }
    else{
    echo “This is a top level category”;
    }

    A top level category will return an ID of 0 for it’s parent category’s ID because it obviously doesn’t have one. This won’t be very useful if you have further nested categories but it did the job for me. That being said you can use it to test if you’re on a sub category.

Leave a comment