Mother category identified as class in the body tag

Hi

Is there a way to insert a class in the body tag related to the mother category in the product archive pages?

I’d like to stylish all products from the same mother category to have a different color…

Is it possible to do this?

I found this

But I couldn’t figure out in witch .php file I should insert this code…

Would you help, please?

Hi @priscilaps,

Thanks for reaching out.

That one needs to modify the actual header.php and <body> tag which isn’t recommended. You can then add this code to your child theme’s functions.php (appending to the end if there is any other codes).

add_filter('body_class', 'mother_category');

function mother_category($classes) {

if ( is_category() ) {

$this_category = get_category($cat);
if ($this_category->category_parent == 0) {
$this_category->category_parent = $cat;
} else {
$parent_category = get_category($this_category->category_parent);
$ParentCatId = $parent_category->cat_ID;
$ParentCatName = $parent_category->slug;
}
$childcategories = array();
$catx = $ParentCatId;
$cats = get_categories('parent='.$catx);
foreach($cats as $cat) {
$childcategories[] = $cat->term_id; } ;
if( is_category( $childcategories ) ) {
$class = 'child-category-of-'.$ParentCatName;
}
        $classes[] = $class;
}

        return $classes;

}

I use the code from the URL you have provided and made it work functions.php. This should serve as a guide on how it should be implemented as functions.php’s code and the proper use of body_class as a filter. We can’t cover any further modification of the code, especially it’s not from us :slight_smile:

Thanks!

thanks… I will try this

You are most welcome!

Got it but not with that code above…

Got it by adding this one below in the function.php in the child theme

function woo_custom_taxonomy_in_body_class( $classes ){
    $custom_terms = get_the_terms(0, 'product_cat');
    if ($custom_terms) {
      foreach ($custom_terms as $custom_term) {

        // Check if the parent category exists:
        if( $custom_term->parent > 0 ) {
            // Get the parent product category:
            $parent = get_term( $custom_term->parent, 'product_cat' );
            // Append the parent class:
            if ( ! is_wp_error( $parent ) )
                $classes[] = 'product_parent_cat_' . $parent->slug;   
        }

        $classes[] = 'product_cat_' . $custom_term->slug;
      }
    }
    return $classes;
}

add_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' );

Great news!
Thanks for sharing the code. This is very useful to other users too.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.