I have spent hours researching how to do this but everything I found explains it in a way that goes over my head. I’m not great with coding but I know how to Inspect element and work from there but that doesn’t help me in this case.

I want to use a different page layout/template on products in a specified category. I am using WooCommerce and I was able to use inspect element to recreate a product page the way I desired. Then I have copied the text into the custom css and it works great. However, this ends up being a Global change.

A majority of my product pages would benefit from having the default template rather than the custom one I made. I want to know how to add the code inside of the brackets so that the custom css (custom template) that I’ve added only gets applied to products in it’s designated category.

I hope all that makes sense. Here are pictures to give you a visual example.

enter image description here

I already know what custom css I want to add to the modified product page template. I hope that designating this custom css to the specific categories is as simple as adding brackets similar to this (sorry, I’m sure it’s way wrong but I see custom css that looks similar to this)

.product.category-2 {
custom css changes here
}

Thanks for taking the time to read this and I appreciate any and all help.

5 Answers
5

Here’s my solution… Added the following to functions.php in my child theme:

add_filter( 'body_class','my_body_classes2' );
function my_body_classes2( $classes ) {

if ( is_product() ) {

    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );

    foreach ($terms as $term) {
        $product_cat_id = $term->term_id;
        $classes[] = 'product-in-cat-' . $product_cat_id;    
    }
}
return $classes;
}

Now whenever you’re viewing a single product page, an additional CSS class for each category the product is in will be added to the <body> tag.

Then if you want to change the styling for any single product pages in category 2 or 4, you can use the following CSS:

.product-in-cat-2 , .product-in-cat-4 {
    color: #ffffff;
}

Leave a Reply

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