WooCommerce - get category for product page

PhpWordpressWoocommerce

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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 - Php

$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 - Php

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.

Solution 4 - Php

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.

/* Post Meta */


if (!function_exists( 'woo_post_meta')) {
	function woo_post_meta( ) {
		global $woo_options;
		global $post;
		
		$terms = get_the_terms( $post->ID, 'product_cat' );
		foreach ($terms as $term) {
			$product_cat = $term->name;
			break;
		}
	
?>
<aside class="post-meta">
	<ul>
		<li class="post-category">
			<?php the_category( ', ', $post->ID) ?>
                        <?php echo $product_cat; ?>
            
		</li>
		<?php the_tags( '<li class="tags">', ', ', '</li>' ); ?>
		<?php if ( isset( $woo_options['woo_post_content'] ) && $woo_options['woo_post_content'] == 'excerpt' ) { ?>
			<li class="comments"><?php comments_popup_link( __( 'Leave a comment', 'woothemes' ), __( '1 Comment', 'woothemes' ), __( '% Comments', 'woothemes' ) ); ?></li>
		<?php } ?>
		<?php edit_post_link( __( 'Edit', 'woothemes' ), '<li class="edit">', '</li>' ); ?>
	</ul>
</aside>
<?php
	}
}


?>

Solution 5 - Php

<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>

Solution 6 - Php

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:

  • key: It can be the product category id (or the slug or the name). Or an array of them. Read the documentation.
  • value: a string containing the classes to add to the body tag. If you want to add more than one class create a string with multiple values separated by a space (see my example below)

So:

// adds a class to the body element based on the product category
add_filter( 'body_class', 'add_body_class_based_on_the_product_category' );
function add_body_class_based_on_the_product_category( $classes ) {

    // only on the product page
    if ( ! is_product() ) {
        return $classes;
    }

    // create an array with the ids (or slugs) of the product categories and the respective class (or classes) to add
    $classes_to_add = array(
        30          => 'class-1',
        'cat_slug'  => 'class-2 class-3',
        32          => 'class-4 class-5',
    );

    // if the product belongs to one of the product categories in the array it adds the respective class (or classes)
    foreach ( $classes_to_add as $product_cat => $new_classes ) {
        if ( has_term( $product_cat, 'product_cat', get_the_ID() ) ) {
             $classes[] = $new_classes;
        }
    }    

    return $classes;
}

The code has been tested and works. Add it to your active theme's functions.php.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionban-geoengineeringView Question on Stackoverflow
Solution 1 - PhpBoxView Answer on Stackoverflow
Solution 2 - PhpJaydip NimavatView Answer on Stackoverflow
Solution 3 - PhpAlreadytakenindeedView Answer on Stackoverflow
Solution 4 - PhpZAA.CCView Answer on Stackoverflow
Solution 5 - PhpAdam ColtonView Answer on Stackoverflow
Solution 6 - PhpVincenzo Di GaetanoView Answer on Stackoverflow