WordPress   

Add product category class to single product in Woocommerce

Sometimes we need to add product category classes to body in woocommerce single product pages for styling or other purposes. Woocoomerce does not provide this functionality by default but luckily we can do this with a small code snippet based on the body_class Woocommerce hook.

  //Add product category class to body in single product
  add_filter('body_class','rp_add_product_category_class_single_product');
  function rp_add_product_category_class_single_product($classes) {
    if (is_singular('product') ) {
        global $post;
        $terms = get_the_terms( $post->ID, 'product_cat' );
        foreach ($terms  as $term  ) {
            $product_cat_slug = $term->slug;
            $classes[] = 'product-'.$product_cat_slug;
        } 
    }
    return $classes;
  }
Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us