For my WC product pages, I need to add a class to the body tag so that I can perform some custom styling. Here’s the function I’m creating for this…
function my_add_woo_cat_class($classes) {
$wooCatIdForThisProduct = "?????"; //help!
// add 'class-name' to the $classes array
$classes[] = 'my-woo-cat-id-' . $wooCatIdForThisProduct;
// return the $classes array
return $classes;
}
//If we're showing a WC product page
if (is_product()) {
// Add specific CSS class by filter
add_filter('body_class','my_add_woo_cat_class');
}
…but how do I get the WooCommerce cat ID?
A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.
Please look into the meta.php file in the “templates/single-product/” folder of the WooCommerce plugin.
$product->get_categories()
is deprecated since version 3.0! Usewc_get_product_category_list
instead.https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html
I literally striped out this line of code from content-single-popup.php located in woocommerce folder in my theme directory.
Since my theme that I am working on has integrated woocommerce in it, this was my solution.
Thanks Box. I’m using MyStile Theme and I needed to display the product category name in my search result page. I added this function to my child theme functions.php
Hope it helps others.
To add custom classes to the body tag you can use the
body_class
hook.To add one or more classes on the product page based on specific product categories you can use the WordPress
has_term
function (to check if a product belongs to that specific product category).For this I created the array
$classes_to_add
where:So:
The code has been tested and works. Add it to your active theme’s functions.php.