2
votes

I'm trying to add classes to the WooCommerce single product pages, specifically the "product" div on the product page, but other elements too - using hooks and filters.

I'm not great with PHP, I'm more of a front-end developer, but I've been tasked with styling WooCommerce to fit in with a custom Wordpress theme.

I've used the below code before to add classes to the body element in Wordpress through the functions.php file. I found the "product" div on the product page in the WooCommerce templates and copied the filter for this, but it doesn't seem to work.

add_filter( 'wc_product_class','my_product_class' );
function my_product_class( $classes ) {
    $classes[] = 'my-product-class';         
    return $classes; 
}

Any help or pointers to what I should be doing to achieve this would be very much appreciated. I'm adding classes with JS for now, but that's probably not a great idea!

1
There is a nice visual guide of hooks here for the Woocommerce Single Product page. businessbloomer.com/…Ozgur Sar
Thank you. I've seen that page before, but it's a help, thanks. I think it's the filters I need rather than the hooks though to add classes. I believe the hooks are for moving content around. I can't seem to find an example of a filter which I can work from to add classes to the various elements on the product page.David Clarke
I think you are looking for these woocommerce.github.io/code-reference/namespaces/…Ozgur Sar

1 Answers

4
votes

The function wc_get_product_class from includes/wc-template-functions.php contains the newer woocommerce_post_class filter hook

So to add a class/classes on the single product page (The "product" div) you could use:

/**
 * WooCommerce Post Class filter.
 *
 * @since 3.6.2
 * @param array      $classes Array of CSS classes.
 * @param WC_Product $product Product object.
 */
function filter_woocommerce_post_class( $classes, $product ) {
    // is_product() - Returns true on a single product page
    // NOT single product page, so return
    if ( ! is_product() ) return $classes;
    
    // Add new class
    $classes[] = 'my-product-class';
    
    return $classes;
}
add_filter( 'woocommerce_post_class', 'filter_woocommerce_post_class', 10, 2 );

Note: the class/classes will also be applied to the related products, generated by a "loop" on the single product page.

To prevent this, use:

function filter_woocommerce_post_class( $classes, $product ) {
    global $woocommerce_loop;
    
    // is_product() - Returns true on a single product page
    // NOT single product page, so return
    if ( ! is_product() ) return $classes;
    
    // The related products section, so return
    if ( $woocommerce_loop['name'] == 'related' ) return $classes;
    
    // Add new class
    $classes[] = 'my-product-class';
    
    return $classes;
}
add_filter( 'woocommerce_post_class', 'filter_woocommerce_post_class', 10, 2 );