WooCommerce - get category for product page

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?


Solution 1:

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>' ); ?>

Solution 2:

$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

Solution 3:

I literally striped out this line of code from content-single-popup.php located in woocommerce folder in my theme directory.

global $product; 
echo $product->get_categories( ', ', ' ' . _n( ' ', '  ', $cat_count, 'woocommerce' ) . ' ', ' ' );

Since my theme that I am working on has integrated woocommerce in it, this was my solution.