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?
How do I find a product category ID in WooCommerce? To find the WooCommerce product category ID, you need to go WooCommerce Dashboard → Products → Categories → hover over a [category name] → click [category name] or click Edit when it appears → find the URL. For example: tag_ID=16 where 16 is the ID of the category.
On your WordPress admin panel, go to Appearance > Customise > WooCommerce to access the settings, and click Product Catalog. Here you will see an option for Shop page display. There are three options in a drop-down – show products, show categories, show categories and products.
A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.
global $post; $terms = get_the_terms( $post->ID, 'product_cat' ); foreach ($terms as $term) { $product_cat_id = $term->term_id; break; }
Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>
$product->get_categories()
is deprecated since version 3.0! Use wc_get_product_category_list
instead.
https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With