59

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?

ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253

6 Answers6

118

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>' ); ?>
Box
  • 2,432
  • 1
  • 18
  • 20
  • Just added this code to "price.php" and when visiting single product page I get this error message: Warning: Invalid argument supplied for foreach(). Do I do something wrong or is this code incompatible with current WC version? – drake035 Jan 03 '15 at 21:58
  • Is there a way to exclude certain categories with this? – JacobTheDev Mar 02 '15 at 22:00
  • This helped me to get the product slug and use it to redirect to category listing after saving a new comment. This was my question if is of any help. http://stackoverflow.com/questions/42014311/wordpress-get-the-category-returns-empty – Carlos Garcia Feb 03 '17 at 04:43
  • This is amazing. I even put cats in arrays for multiple categories. Excellent answer! – yanike Mar 30 '21 at 05:07
14

$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

Blue
  • 22,608
  • 7
  • 62
  • 92
Jaydip Nimavat
  • 603
  • 9
  • 19
9

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.

Zahari Kitanov
  • 510
  • 7
  • 15
5

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


?>
ZAA.CC
  • 53
  • 1
  • 5
2
<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>
Adam Colton
  • 189
  • 2
  • 5
0

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.

Vincenzo Di Gaetano
  • 3,892
  • 3
  • 13
  • 32