Add a body class related to the product category in WooCommerce

How can I add a body class related to the product category slug?

Thank you!

Related posts

2 comments

  1. Add this to your functions.php

    add_filter( 'body_class', 'wc_cat_names' );
    function wc_cat_names( $classes ) {
        if(is_product()){
        global $post;
        $terms = get_the_terms( $post->ID, 'product_cat' );
            foreach ($terms as $term) {
                $classes[] = $term->slug;
            }
        }
        return $classes;
    }
    

    This one will work only in woocommerce product page and Yes I tested this on my test site.

  2. There is a pretty good guide for doing exactly this on the WordPress support site: Modify body_class() output to show category-{slug} for single posts

    I have altered the code from the post to suit your needs:

    add_filter('body_class','add_category_to_single');
    function add_category_to_single($classes, $class) {
        if (is_single() ) {
            global $post;
            foreach((get_the_category($post->ID)) as $category) {
                echo $category->cat_name . ' ';
                // add category slug to the $classes array
                $classes[] = $category->slug;
            }
        }
        // return the $classes array
        return $classes;
    }
    

Comments are closed.