Site icon Experience Wordpress Developer Online – Design Develop and Maintenance Support

Rename “Add to Cart” Button if Product Already at WooCommerce Cart

If one a product is already in user cart, displaying a different text instead of default “Add to Cart” text of Add to Cart Button. So you easily communicate to the user a product is already in the Cart before re-adding it or increasing its quantity from the Shop/Category/Loop and Single Product pages.

It is too simple in WooCommerce because WooCommerce have exact filter hook to change this add to cart button text. one filter hook for the Single Product page and another filter hook for the other pages such as Shop.

Before changing Add to Cart button text, we want to check if the item is already in user cart. Then according to the status of the item, we want to return the text for the Add to Cart button.

Add this code in your theme’s functions.php file of your active child theme (or theme).


//Change the add to cart text on single product pages

add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_cart_button_single_product' );
 
function 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 = __('Already in Cart. Add again?', 'woocommerce');
        }
    }
     
    return $label;
 
}
 
// Change the add to cart text on product archives
 
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_cart_button_loop', 99, 2 );
 
function custom_add_cart_button_loop( $label, $product ) {
     
    if ( $product->get_type() == 'simple' && $product->is_purchasable() && $product->is_in_stock() ) {
         
        foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            if( get_the_ID() == $_product->get_id() ) {
                $label = __('Already in Cart. Add again?', 'woocommerce');
            }
        }
         
    }
     
    return $label;
     
}
Exit mobile version