Woo: Rename “add to cart” button if product already in cart

smartsovereign
18 May 2022

Credit: https://businessbloomer.com/ for this one. Check out his website, he has hundreds of useful Woo snippets.

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.

This is a front end snippet.

<?php

// Part 1
// Edit Single Product Page Add to Cart
 
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 = __('Add again?', 'woocommerce');
      }
   }
    
   return $label;
 
}
 
// Part 2
// Edit Loop Pages Add to Cart
 
add_filter( 'woocommerce_product_add_to_cart_text', 'bbloomer_custom_add_cart_button_loop', 99, 2 );
 
function bbloomer_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 = __('Add again?', 'woocommerce');
         }
      }
       
   }
    
   return $label;
    
}

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy