Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 625
ban-geoengineering Avatar asked Mar 08 '13 20:03

ban-geoengineering


People also ask

How do I get product category in WooCommerce?

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.

How do I show product categories on WooCommerce shop page?

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.


2 Answers

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>' ); ?> 
like image 61
Box Avatar answered Sep 19 '22 05:09

Box


$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

like image 30
Jaydip Nimavat Avatar answered Sep 23 '22 05:09

Jaydip Nimavat