Search code examples
phpwordpresswoocommerceproductcart

WooCommerce: change the add to cart text when the product is already in cart


I am having an issue changing the text of the "Add to cart" button in WooCommerce/WordPress.

Currently the code below, I want it so that if a product is already in cart, the "Add to cart" button reflects that by changing the text to state it's already in the cart.

At the moment, it remains "Add to cart" even if product is in cart. What is strange is if I remove the if condition, the text changes, so I am assuming there's something wrong with the if condition but I can't see any issue with it.

add_filter('woocommerce_product_add_to_cart_text', 'woocommerce_custom_add_to_cart_text');
function woocommerce_custom_add_to_cart_text($add_to_cart_text, $product_id) {
    global $woocommerce;
    
    foreach($woocommerce->cart->get_cart() as $key => $val ) {
        $_product = $val['data'];
 
        if($product_id == $_product->id ) {
            $add_to_cart_text = 'Already in cart';
        }
        
    return $add_to_cart_text;
    }
}

Solution

    • $_product->id should be $_product->get_id()
    • Use return outside the foreach loop
    • global $woocommerce is not necessary
    • Second parameter from woocommerce_product_add_to_cart_text filter hook is $product, not $product_id

    So you get

    function woocommerce_custom_add_to_cart_text( $add_to_cart_text, $product ) {
        // Get cart
        $cart = WC()->cart;
        
        // If cart is NOT empty
        if ( ! $cart->is_empty() ) {
    
            // Iterating though each cart items
            foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                // Get product id in cart
                $_product_id = $cart_item['product_id'];
         
                // Compare 
                if ( $product->get_id() == $_product_id ) {
                    // Change text
                    $add_to_cart_text = __( 'Already in cart', 'woocommerce' );
                    break;
                }
            }
        }
    
        return $add_to_cart_text;
    }
    add_filter( 'woocommerce_product_add_to_cart_text', 'woocommerce_custom_add_to_cart_text', 10, 2 );