There should already be a special body class. Look at the html. For example, I have a “Clothing” category on my demo site and I found these on the body tag in the html: tax-product_cat term-clothing
So you can just target those specific products on the category page like so: .tax-product_cat.term-clothing li.product.
Thread Starter
woober
(@woober)
Thanks for the reply.
It shows the category page im in and not the category-classes which are within the category.
E.g If Men & Women category has clothing category as parent, then if i enter clothing, then i dont see Men or Women class in the body + the i want the Men products to have a class, not the body.
<ul class="products"><li class="men">
Do you need to target the entire product listing or the specific products that match a category? If a product has multiple categories(even sub-categories), all of them should be added as a class. In this case, the parent is ‘bicycles’ and the child is ‘fixed gear’:
<li class= “product_cat-bicycles product_cat-fixed-gear”>
Thread Starter
woober
(@woober)
Thanks for the reply Thomas.
I need all ‘fixed gear’ bicycles to have added a class in the category page, as in your example.
Not sure this matters: These bikes will also be shown elsewhere on the site, like at the frontpage under ‘Most bought’ etc. so its not only under the parent category.
Pretty sure this already exists: http://cld.wthms.co/XRDn/5X5WEvPf
If you don’t see it for some reason, this should do the trick:
function wc_ninja_add_category_html_class( $classes ) {
global $post;
$categories = get_the_terms( $post->ID, 'product_cat' );
if ( $categories ) {
foreach ( $categories as $category ) {
$classes[] = 'product-category-' . $category->slug;
}
}
return $classes;
}
add_filter( 'post_class', 'wc_ninja_add_category_html_class' );
Thread Starter
woober
(@woober)
Thanks Caleb.
You are absolutely right. Its already there, its just because my these removes them. Thanks again, i will have to talk with them about it 🙂