Home » WooCommerce: Category as “Body” Class @ Single Product Page

WooCommerce: Category as “Body” Class @ Single Product Page

by Tutor Aspire

A Business Bloomer fan asked me an interesting question this week: how to apply CSS on the single product page based on the product category? Well, the answer is pretty simple: if we’re able to add the category name to the HTML “body”, this can then be targeted in your custom CSS. So, let’s see how this is done!

WooCommerce: Add Product Category Name to Body CSS Classes

PHP Snippet: Add WooCommerce Product Category as Body CSS Class @ Single Product Page

Thankfully, there was already some literature available on GitHub, and despite being 5 years old it still works like a charm. So, many thanks Michael Krapf 🙂

/**
 * @snippet       Product Category > Body CSS Class @ Single Product
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @testedwith    WooCommerce 3.9
 * @donate $9     https://tutoraspire.com
 */
 
add_filter( 'body_class', 'tutoraspire_wc_product_cats_css_body_class' );
 
function tutoraspire_wc_product_cats_css_body_class( $classes ){
  if ( is_singular( 'product' ) ) {
    $current_product = wc_get_product();
    $custom_terms = get_the_terms( $current_product->get_id(), 'product_cat' );
    if ( $custom_terms ) {
      foreach ( $custom_terms as $custom_term ) {
        $classes[] = 'product_cat_' . $custom_term->slug;
      }
    }
  }
  return $classes;
}

You may also like