Wordpress - How To Get Parent Category Slug of Current Post

You will need to use the ID value returned by $category[0]->category_parent and pass it through get_term(). Example:

$category = get_the_category(); 
$category_parent_id = $category[0]->category_parent;
if ( $category_parent_id != 0 ) {
    $category_parent = get_term( $category_parent_id, 'category' );
    $css_slug = $category_parent->slug;
} else {
    $css_slug = $category[0]->slug;
}

You will need to query for the parent category data. get_category is pretty much built for doing that.

$category = get_the_category(); 
$parent = get_category($category[0]->category_parent);
echo $parent->slug;

That will return the immediate parent of the category. That is given this set of categories:

  • Cartoon
    • Dog
      • Scooby

The code above will return "Dog" if you give it the ID for "Scooby". If you want the topmost parent category-- "Cartoon"-- no matter how deep the nesting, use something like this:

$category = get_the_category(); 
$parent = get_ancestors($category[0]->term_id,'category');
if (empty($parent)) {
  $parent[] = array($category[0]->term_id);
}
$parent = array_pop($parent);
$parent = get_category($parent); 
if (!is_wp_error($parent)) {
  var_dump($parent);
} else {
  echo $parent->get_error_message();
}

That also has the advantage of relatively neat error handling.

Tags:

Categories