Add a body class related to the product category in WooCommerce olatechproJune 23, 20231 Views How can I add a body class related to the product category slug? Thank you! Post Views: 1 Related postsGet rid of this Strict Standards warningWooCommerce: get_current_screen not working with multi languageCan’t login on WordPressForce HTTPS using .htaccess – stuck in redirect loopWordPress: Ajax not working to insert, query and result dataHow Can I pass an image file to wp_handle_upload?
Add this to your functions.php add_filter( 'body_class', 'wc_cat_names' ); function wc_cat_names( $classes ) { if(is_product()){ global $post; $terms = get_the_terms( $post->ID, 'product_cat' ); foreach ($terms as $term) { $classes[] = $term->slug; } } return $classes; } This one will work only in woocommerce product page and Yes I tested this on my test site.
There is a pretty good guide for doing exactly this on the WordPress support site: Modify body_class() output to show category-{slug} for single posts I have altered the code from the post to suit your needs: add_filter('body_class','add_category_to_single'); function add_category_to_single($classes, $class) { if (is_single() ) { global $post; foreach((get_the_category($post->ID)) as $category) { echo $category->cat_name . ' '; // add category slug to the $classes array $classes[] = $category->slug; } } // return the $classes array return $classes; }
Add this to your functions.php
This one will work only in woocommerce product page and Yes I tested this on my test site.
There is a pretty good guide for doing exactly this on the WordPress support site: Modify body_class() output to show category-{slug} for single posts
I have altered the code from the post to suit your needs: