How to customize style for products of specific category in WooCommerce?

In this tutorial; We will learn how to customize the style products of a specific category in Woocommerce. By default, the products of all categories have same style. Also the body tag only contains product specific and product generic classes.

We can style all the products individually with post id class but there isn’t any class which will differentiate products of a specific category. With product id whenever we add a new product we have to add a specific rule for that specific product.

Following is a default view of all the classes on product page. We are using firebug to see the code.

 

You can see there is no category specific class.

Now we’ll add category to which this product belongs in the body tag. To do this add the following lines of code at the end of your theme’s functions.php file:

// add taxonomy term to body_class
function woo_custom_taxonomy_in_body_class( $classes ){
  if( is_singular( 'product' ) )
  {
    $custom_terms = get_the_terms(0, 'product_cat');
    if ($custom_terms) {
      foreach ($custom_terms as $custom_term) {
        $classes[] = 'product_cat_' . $custom_term->slug;
      }
    }
  }
  return $classes;
}
add_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' );

Add the above code in your theme’s functions.php file. Appearance –> editor –> functions.php

Now if you go to product page again and inspect element you’ll see product category has been added to body tag.

 

Now you can write style rules inherited from this category class and the style rules will only be applied to products of a specific category.

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

Leave a Comment

Your email address will not be published. Required fields are marked *