Add Category Class to Body Classes of Woocommerce for Single Product Page

To change a design of single product page for some particular category of products on Woocommerce shop I often need this code to be put into functions.php of my WordPress child theme.

// add taxonomy term of products category to body classes
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' );

Taken from here.

Share:
This entry was posted in WordPress and tagged . Bookmark the permalink.

2 Responses to Add Category Class to Body Classes of Woocommerce for Single Product Page

  1. Mehrdad says:

    Hi.

    This is working perfectly but how can I also add the parent category to the single product pages?

    For example I have “Fabrics” Category and inside that category I have “Fine Fabrics” & “Regular Fabrics”
    I want to see the following in the body of my single product page:

    So that when I target “Fabrics” in my CSS it will effect all the single products in the Parent “Fabrics” category.

    Thanks
    Mehrdad

Leave a Reply

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