Home » WooCommerce: Rename “Add to Cart” Button if Product Already @ Cart

WooCommerce: Rename “Add to Cart” Button if Product Already @ Cart

by Tutor Aspire

When talking about UX, or for very specific WooCommerce shops, you might need to tell 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.

The “Add to Cart” button label comes with a filter (actually 2 filters, one for the Single Product page and another for the other pages such as Shop), so all we need to do is targeting those two hooks. We will “filter” the label text in case the product is already in the Cart, and return that back to WooCommerce. If this sounds like Japanese to you (hey, unless you’re from Japan!) don’t worry – simply copy/paste the snippet below as per below instructions.

Enjoy!

 

Change the WooCommerce Add to Cart button label if Product is already in the Cart

PHP Snippet: Rename WooCommerce “Add to Cart” Button if Product Already in Cart

/**
* @snippet       Change "Add to Cart" Button Label if Product Already @ Cart
* @how-to        Get tutoraspire.com FREE
* @author        Tutor Aspire
* @compatible    WC 5.0
* @donate $9     https://www.tutoraspire.com
*/

// Part 1
// Single Product Page Add to Cart

add_filter( 'woocommerce_product_single_add_to_cart_text', 'tutoraspire_custom_add_cart_button_single_product', 9999 );

function tutoraspire_custom_add_cart_button_single_product( $label ) {
   if ( WC()->cart && ! WC()->cart->is_empty() ) {
      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?';
            break;
         }
      }
   }
   return $label;
}

// Part 2
// Loop Pages Add to Cart

add_filter( 'woocommerce_product_add_to_cart_text', 'tutoraspire_custom_add_cart_button_loop', 9999, 2 );

function tutoraspire_custom_add_cart_button_loop( $label, $product ) {
   if ( $product->get_type() == 'simple' && $product->is_purchasable() && $product->is_in_stock() ) {
      if ( WC()->cart && ! WC()->cart->is_empty() ) {
         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?';
               break;
            }
         }
      }
   }
   return $label;
}

You may also like