How To Get Parent Category Slug of Current Post

The question:

My theme has styling by category using the following code, which inserts the current category’s slug as a CSS class.

<div class="CategorySpecificStyle 
    <?php $category = get_the_category(); echo $category[0]->slug; ?>">
        <?php echo $category[0]->cat_name; ?>
</div> 

Now i’m about to add a large number of new sub-categories, and it seems silly to add them all in CSS when I should be able to just select the parent category of the current post and apply styles to that.

I’ve been able to get the parent category’s name:

$parentcat = get_cat_name($category[0]->category_parent);

But spaces (and capitalization) is an issue… And I can’t seem to get the parent category’s slug.

I know i’m probably missing a simple step somewhere, but any insight would be greatly appreciated.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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;
}

Method 2

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.

Method 3

I like the previous answer from @s_ha_dum, but for getting the top-level category regardless of depth, I used what I consider to be a simpler solution:

$cats = get_the_category();
foreach ( $cats as $cat ) {
    if ( $cat->category_parent == 0 ) {
        return $cat->name; // ...or whatever other attribute/processing you want
    }
}
return ''; // This was from a shortcode; adjust the return value to taste

Method 4

If it can help somebody… to get child cat or parent, depending on the 0 or 1 you put on the $category

$category = get_the_category();
$parent = get_cat_name( $category[0]->category_parent );
if( ! function_exists('get_cat_slug') )
{
    function get_cat_slug($cat_id) {
        $cat_id = (int) $cat_id;
        $category = &get_category($cat_id);
        return $category->slug;
    }
}
if ( !empty($parent) ) {
    $output .= '<H2>' . esc_html( $category[1]->name ) . '</H2>';                               
} else {
    $output .= '<H2>' . esc_html( $category[0]->name ) . '</H2';
}

Method 5

You can simplify it like this:

  $category   = get_the_category();
  $cat_parent = $category[0]->category_parent;
  $category   = $cat_parent != 0 ? get_term($cat_parent, 'category')->slug : $category[0]->slug;

Method 6

The following function is adapted to return the root category:

function get_root_category($category = null) {
  if (!$category) $category = get_the_category()[0];
  $ancestors = get_ancestors($category->term_id, 'category');
  if (empty($ancestors)) return $category;
  $root = get_category(array_pop($ancestors)); 
  return $root;
}

Usage:
get_root_category()->slug

Method 7

All the answers above are good except the “category_parent” now replaced with “parent” from 2018!

In 2021

$custom_tax = 'books_category'; //Custom taxonomy

//Get the terms from post ID
$terms = get_the_terms( $post->ID, $custom_tax );
$parent_id = $terms[0]->parent;

if ($parent_id != 0){
    $parent = get_term( $parent_id, $custom_tax);
    echo $parent->slug;
}

Method 8

For Taxonomies in 2021

$capitulos = get_the_terms( $post->ID, 'capitulos' );
if ($capitulos) {
foreach($capitulos as $capitulo) { if ($capitulo->parent == 0) 
echo '<a href="' . get_term_link($capitulo->term_id) . '">' . $capitulo->name . '</a> ';}
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment