Monday, May 9, 2022

[FIXED] How to add classes to WooCommerce single product pages

Issue

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!


Solution

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


Answered By - 7uc1f3r
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.