0

I figured out how to assign a template to a product category (from this thread Different template of products for specific category. WooCommerce), but I'm wondering if I can assign a custom template to specific products.

EDIT: For more clarity, I want to have a certain style applied to the category page, but when I click on one of those products, I want to keep that same style.

2
  • so basically you want all products of a certain category to have a differente style?
    – dbeja
    Commented Dec 19, 2012 at 19:55
  • @dbeja That is correct, I want products of category X to have a custom single-product.php template
    – Ten Sleep
    Commented Dec 19, 2012 at 20:22

1 Answer 1

2

If the changes you need are strictly CSS, you can add the category names as classes to the body_class via the body_class filter.

add_filter('body_class','wpa76627_class_names');
function wpa76627_class_names( $classes ) {
    if( is_singular( 'product' ) ):
        global $post;
        foreach( get_the_terms( $post->ID, 'product_cat' ) as $cat )
            // maybe you want to make this more unique, like:
            // $classes[] = 'product-category-' . $cat->slug;
            $classes[] = $cat->slug;
    endif;
    return $classes;
}

This code checks if we are viewing a single product page, then loops over all product_cats, adding the slugs as classes to the body tag. This could also be adapted for any post type or taxonomy.

6
  • Would I add this to my theme functions file?
    – Ten Sleep
    Commented Dec 19, 2012 at 20:24
  • And I'm not quite there yet. Do I change wpa76627_class_names or slug to the category name?
    – Ten Sleep
    Commented Dec 19, 2012 at 20:30
  • yes, you can just copy/paste that into your functions.php file. you don't have to change anything if you don't want to. in your style.css file, you can target items via a selector like body.some-category-slug h1.product-title to style it per-category
    – Milo
    Commented Dec 19, 2012 at 20:37
  • I see what you mean now. I added it to the functions file but when I view source the body tag does not have any classes attached to it.
    – Ten Sleep
    Commented Dec 19, 2012 at 20:40
  • your theme has to have the body_class function: <body <?php body_class(); ?>>
    – Milo
    Commented Dec 19, 2012 at 20:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.