get parent_category class in loop

First you would need to check if the category has children, if it does then we can show a few things. Below is a helpful function to check just that.

function category_has_children( $term_id = 0, $post_type="post", $taxonomy = 'category' ) {
    $children = get_categories( array( 'child_of' => $term_id, 'type' => $post_type, 'taxonomy' => $taxonomy ) );
    return ( $children );
}

By adding this somewhere in your functions.php file, you can then call it and pass it a few things. It returns either true the category does have children or false if not. Below I’m assuming the $cat that you’re passing into get_category() in your question above is a parent category ID, if not you need to somehow get the parent ID ( if $cat is an object, check if $cat->parent is something other than 0 ). If $cat has a parent we know it has children, if the parent is 0, we must check if it has children.

<?php
    $cat           = get_queried_object();
    $classes        = "current_{$cat->slug}";
    if( 0 == $cat->parent ) {
        $classes   .= ( category_has_children( $cat->term_id ) ? ' has_children' : '' );
    } else {
        $parent     = get_category( $cat->parent );
        $classes    = "parent_{$parent->slug} is_child";
        $classes   .= ( category_has_children( $cat->term_id ) ? ' has_children' : '' );
    }
?>
    <a href="#" class="<?php echo $classes; ?>"><?php echo single_cat_title( '' ); ?></a>

First we apply a class of the current category. IF the current category does not have a parent ( is a top-level category ) then we check if it has children and apply a class if it does. ELSE the current category does have a parent so we first get the parent and add 2 classes, 1 of the parent slug and another letting us know that it is a child. Finally, IF the child category also has children, add the class has_children ELSE do nothing.


get_queried_object() Codex – This will explain it in more depth but basically ( pulled from The Codex ) will get some generic information:

  • if you’re on a single post, it will return the post object
  • if you’re on a page, it will return the page object
  • if you’re on a category archive, it will return the category object
  • if you’re on an author archive, it will return the author object