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
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;
}
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;
}
-
-
Sorry, edited the code to work (was missing the
$i++
) but the code from Vinod is also elegant :) Apr 28, 2017 at 2:27 -