if product is in cart add class to add to cart button in woocommerce

4k Views Asked by At

I'm working on woocommerce project and I want to add a new class on Add to Cart button if product is already added in cart, Can you help me to find out with this.

I'm changing right now using this code

add_filter( 'woocommerce_product_single_add_to_cart_text', 'bbloomer_custom_add_cart_button_single_product' ); 
function bbloomer_custom_add_cart_button_single_product( $label ) {

foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
    $product = $values['data'];
    if( get_the_ID() == $product->get_id() ) {
        $label = __('Added', 'woocommerce');
    }
}

return $label; }

text is changing but I want add class so I can add my css style

please help Thank You

1

There are 1 best solutions below

0
hemnath mouli On

The add to cart template which is in woocommerce/templates/loop/add-to-cart.php has a filter. So we can also over write the class using add_filter function in functions.php.

function woocommerce_custom_add_to_cart_class ( $html, $product, $args ) {
    // Define the classes to be added
    $class_to_append = "this_guys_in_cart";

    // Check if product is in cart
    $in_cart = WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) );

    if ( $in_cart != '' ) {
        // Append the extra class
        $args['class'] = $args['class']." {$class_to_append}";

        $html = sprintf( '<a href="%s" data-quantity="%s" class="%s" %s>%s</a>',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ),
            esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ),
            isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
            esc_html( $product->add_to_cart_text() )
        );
    }

    // Return Add to cart button
    return $html;
}

add_filter( "woocommerce_loop_add_to_cart_link", "woocommerce_custom_add_to_cart_class", 10, 3 );

Note: This method is not recommended if add-to-cart.php filte is modified in theme templates