Site logo

Archived topic

Conditional formatting of woo product by category

6 replies · Started by David on June 9, 2017

Viewing posts 1–7 of 7

Hi Guys

i know this is a little off plan in regards to GP but i hope you can help or tell me if i need to commission some custom development.

I currently use the following CSS to format the background of the shop page product images. All my product images are transparent PNG so it works very nicely.

CSS:

.woocommerce ul.products li.product a img{
    width:100%;
    height:auto;
    display:block;
    margin: auto;
    background-color: rgb(255,220,220);
}

I have a requirement to change the colour depending on the category of the product. Scouring the web i found the following code that adds a custom taxonomy to the body class.

PHP:

// add taxonomy term to body_class
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' );

However i dont know where to go from here?

Any help or pointers appreciated

regards

David

Hi David,

Can you see the class being added to the body?: product_cat_whatever

Nope
=\

Hi Tom

apologies - they show up on the Single Product page.....
What i am trying to achieve is in the shop loop, which would allow me to style each product by category.
I am still getting the gist of all this - so really need assist with the correct php to move forward.

appreciate any assistance

regards

David

Hmm, perhaps instead of body_class try filtering into post_class.

Hi Tom - thats great yes of course it needed to be the post class. (like i knew that! lol)
The script didn't work. So i trawled around and found a guide in wordpress codex for adding classes. And tweaked it to this:

// add product category name to post class
function diggs_category_id_class( $classes ) {
    global $post;
    $product_cats = get_the_terms( $post->ID, 'product_cat' );
    if( $product_cats ) foreach ( $product_cats as $category ) {
        $classes[] = 'diggsprod_cat_'.$category->slug;
    }
    return $classes;
}
add_filter( 'post_class', 'diggs_category_id_class' );

I can now customise categorised products using CSS:

li.diggsprod_cat_soap img {
background-color: rgb(255,220,220);
}

Next trick is custom product tags that can be used to identify different qualities of a product.

Thanks for the help - maybe someone else may find this of interest.

David

Awesome! Thanks for posting your solution :)

This archived topic is closed to new replies.