1

I'm finding this next to impossible to find any info on. I'm looking for a way to assign each category level a number and then add that number to the body class. e.g. the parent category archive would show the class .catlevel-1, whereas the child category archive would show class .catlevel-2 ... and so on.

2 Answers 2

3

You can achieve this by using the following custom code. You can use the code by adding it in the functions.php file of child theme or in the custom plugin file.

add_filter( 'body_class', 'custom_cat_archiev_class' );
function custom_cat_archiev_class( $classes ) {
    if ( is_category() ) {
        $cat = get_queried_object();
        $ancestors = get_ancestors( $cat->term_id, 'category', 'taxonomy' );
        $classes[] = 'catlevel-' . ( count( $ancestors ) + 1 );
    }
    return $classes;
}
2
  • This function works well.
    – Pete
    Apr 27, 2017 at 23:41
  • How would be applied to specific custom taxonomies?
    – Pete
    Nov 24, 2018 at 20:23
-1

Interesting! It's not that hard, you will need to use the filter body_class:

add_filter('body_class', 'category_level_as_class');
function category_level_as_class($classes) {

        //First check if we're at a category archive page
        if (is_category()) {
                //Set our counter
                $i = 1;

                //Get current category parent
                $category = get_the_category();
                $parent = $category[0]->parent;

                //Loop through categories parent
                while ($parent > 0) {
                        $i++;
                        //Now get parent category info
                        $category = get_category($parent);
                        $parent = $category->parent;
                }

                //Add the class
                $classes[] = 'catlevel-' . $i;
        }

        return $classes;
}
3
  • This gives the body class catlevel-1 for every cat level.
    – Pete
    Apr 27, 2017 at 23:40
  • Sorry, edited the code to work (was missing the $i++) but the code from Vinod is also elegant :) Apr 28, 2017 at 2:27
  • Sorry still doesn't work now only gives catlevel-2 for every cat level
    – Pete
    Apr 28, 2017 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.