2

When Ajax add to cart functionality is active on my WooCommerce store, on Ajax add to cart first click It shows a checked icon symbol like:
Add to Cart Button

The code below changes the add to button cart text to "Seçildi !" if product is already in to cart, only after refreshing page like:
secildi

//Rename the button on the Product page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'ts_product_add_cart_button' );
 
function ts_product_add_cart_button( $label ) {
    
   foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
      $product = $values['data'];
      if( get_the_ID() == $product->get_id() ) {
         $label = __('Seçildi !', 'woocommerce');
      }
   }
    
   return $label;
 
}
 
//Rename the button on the Shop page 
add_filter( 'woocommerce_product_add_to_cart_text', 'ts_shop_add_cart_button', 99, 2 );
 
function ts_shop_add_cart_button( $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 = __('Seçildi !', 'woocommerce');
         }
       }    
   }
    return $label;    
}

But if you don't refresh the page the button remains like before with the checked icon symbol.

What I would like is to change add to cart button with the quantity that has been added for this product like:

3 in cart

Is this possible? What do I need to change? Any help is appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
musa baltaci
  • 139
  • 1
  • 10

1 Answers1

2

You can use WC woocommerce_product_add_to_cart_text action hook and you can get wc cart loop through all products and compare path second params $prodcuct object. check below code. code will go active theme functions.php file.

function change_add_to_cart_text_if_product_already_in_cart( $add_to_cart_text, $product ) {    
    if ( WC()->cart ) {
        $cart = WC()->cart; // Get cart
        if ( ! $cart->is_empty() ) {
            foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                $_product_id = $cart_item['product_id'];
                if ( $product->get_id() == $_product_id ) {
                    $add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
                    break;
                }
            }
        }
    }
    return $add_to_cart_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );

Updated ( as per OP request how to change text quick on click with quantity ).

There is two way You can do this.

  1. you can use woocommerce_loop_add_to_cart_args and add product qty attribute and based on that you can display.

     function add_product_qty( $args, $product ){
         if ( WC()->cart ) {
             $cart = WC()->cart; // Get cart
             if ( ! $cart->is_empty() ) {
                 foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                     $_product_id = $cart_item['product_id'];
                     if ( $product->get_id() == $_product_id ) {
                         $args['attributes']['data-product-qty'] = $cart_item['quantity'];
                     }else{
                         $args['attributes']['data-product-qty'] = 0;
                     }
                 }
             }else{
                 $args['attributes']['data-product-qty'] = 0;
             }
         }
         return $args;
     }
     add_filter( 'woocommerce_loop_add_to_cart_args', 'add_product_qty', 10, 2 );
    
     add_action( 'wp_footer', 'ajax_button_text_quick_change_js_script' );
     function ajax_button_text_quick_change_js_script() {
         ?>
         <script>
             (function($) {
    
                 $(document.body).on('click', '.ajax_add_to_cart', function(event){
                     $this = $(this);
                     var product_qty = parseInt($this.attr('data-product-qty')) + 1;
                     $this.attr('data-product-qty',product_qty);
                     var buttonText = '<span class="add_to_cart_text product-is-added">('+product_qty+') Already in cart</span><i class="cart-icon pe-7s-cart"></i>';
                     $this.html(buttonText).attr('data-tip','('+product_qty+') Already in cart');
                 });
    
             })(jQuery);
         </script>
         <?php
     }
    
  2. You can use added_to_cart jQuery event that triggers after adding to the cart you call ajax and get add_to_cart_text in response.

     add_action( 'wp_footer', 'ajax_button_text_js_script' );
     function ajax_button_text_js_script() {
         ?>
         <script>
             (function($) {
    
                 $(document.body).on('added_to_cart', function(event, fragments, cart_hash, button){
    
                     var product_id  = button.data('product_id'),
                         product_qty = button.data('quantity');
    
                     button.addClass('loading');
    
                     $.ajax({
                         url: "<?php //echo admin_url('admin-ajax.php'); ?>",
                         method: 'POST',
                         data:{action:'change_add_to_cart_text',product_id:product_id},
                         dataType: "json",
                         success: function( response ){
                             var buttonText = '<span class="add_to_cart_text product-is-added">'+response.data.button_text+'</span><i class="cart-icon pe-7s-cart"></i>';
                             button.html(buttonText).attr('data-tip',response.data.button_text);
                             button.removeClass('loading');
                         },error: function (jqXHR, exception) {
                             var msg = '';
                             if (jqXHR.status === 0) {
                                 msg = 'Not connect.\n Verify Network.';
                             } else if (jqXHR.status == 404) {
                                 msg = 'Requested page not found. [404]';
                             } else if (jqXHR.status == 500) {
                                 msg = 'Internal Server Error [500].';
                             } else if (exception === 'parsererror') {
                                 msg = 'Requested JSON parse failed.';
                             } else if (exception === 'timeout') {
                                 msg = 'Time out error.';
                             } else if (exception === 'abort') {
                                 msg = 'Ajax request aborted.';
                             } else {
                                 msg = 'Uncaught Error.\n' + jqXHR.responseText;
                             }
                             console.log(msg);
                         },
                     });
                 });
    
             })(jQuery);
         </script>
         <?php
     }
    
     add_action('wp_ajax_change_add_to_cart_text', 'change_add_to_cart_text');
     add_action('wp_ajax_nopriv_change_add_to_cart_text', 'change_add_to_cart_text');
    
     function change_add_to_cart_text(){
    
         $product_id = $_POST['product_id'];
    
         if ( WC()->cart ) {
             $cart = WC()->cart; // Get cart
             if ( ! $cart->is_empty() ) {
                 foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                     $_product_id = $cart_item['product_id'];
                     if ( $product_id == $_product_id ) {
                         $add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
                         break;
                     }
                 }
             }
         }
    
         wp_send_json_success(array(
             'button_text' => $add_to_cart_text
         ));
     }
    

This below code only for OP site.

add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_add_quantity_fields', 99, 2 );
function custom_add_quantity_fields($html, $product) {
    //add quantity field only to simple products
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {

        if ( WC()->cart ) {
            $cart = WC()->cart; // Get cart
            if ( ! $cart->is_empty() ) {
                foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                    $_product_id = $cart_item['product_id'];
                    if ( $product->get_id() == $_product_id ) {
                        $data_product_qty = $cart_item['quantity'];
                    }else{
                        $data_product_qty = 0;
                    }
                }
            }else{
                 $data_product_qty = 0;
            }
         }

        //rewrite form code for add to cart button
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
        $html .= woocommerce_quantity_input( array(), $product, false );
        $html .= '<button type="submit" data-quantity="1" data-product_id="' . $product->get_id() . '" class="button alt ajax_add_to_cart add_to_cart_button product_type_simple" data-product-qty="'.$data_product_qty.'">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}   

Tested and works.

Shop Page

Product Page

Bhautik
  • 11,125
  • 3
  • 16
  • 38
  • Thx @Bhautik, it works greate but, at the first clik, add to cart button just shows checkt symbol, after refreshing page, it shows (x) Already in cart. Is the result the same in your test? – musa baltaci Apr 01 '21 at 16:38
  • Yes same for me. do you want to change when adding to cart( I mean on click? ) – Bhautik Apr 01 '21 at 16:42
  • i mean when click to add to cart button, the button turning into checkt symbol, there is no quantity and already in cart text. After refreshing page, i cen see the quantitty and Already in cart text. i want to do this on first click. İ dont need to checkt symbol, i need quantitiy and already in cart text. :) thx. – musa baltaci Apr 01 '21 at 16:51
  • There is a little more code to do that. you can use the `added_to_cart` jQuery event that triggers after adding to the cart and based on that you can change. You can check more here [Change custom Ajax Add to Cart button text after add to cart in WooCommerce](https://stackoverflow.com/questions/65747650/change-custom-ajax-add-to-cart-button-text-after-add-to-cart-in-woocommerce) and here [Add a quantity field to Ajax add to cart button on WooCommerce shop page](https://stackoverflow.com/questions/48722178/add-a-quantity-field-to-ajax-add-to-cart-button-on-woocommerce-shop-page) – Bhautik Apr 01 '21 at 16:54
  • Can you tell me how to search or I would be glad if you can give an example. – musa baltaci Apr 01 '21 at 16:57
  • Check the question and answers that I mentioned in the above comments. – Bhautik Apr 01 '21 at 16:58
  • at this link second answer, jquery code makes what i want, now i need to marge this code with that. Could you help me . Thx. https://stackoverflow.com/questions/65747650/change-custom-ajax-add-to-cart-button-text-after-add-to-cart-in-woocommerce – musa baltaci Apr 01 '21 at 17:06
  • Sure I will back to you. – Bhautik Apr 01 '21 at 17:11
  • @musa baltaci does my answer help? – Bhautik Apr 01 '21 at 19:56
  • 1. answer is work but, after click to button, the button show (nan) Already in cart. and when refreshing page the button shows add to cart again. @Bhautik – musa baltaci Apr 01 '21 at 20:19
  • 2. answer not working. everything is as before. not any change. @Bhautik. – musa baltaci Apr 01 '21 at 20:20
  • if i use this function "function change_add_to_cart_text_if_product_already_in_cart" with your 1. answer, its make what i want but, i have to solve (NaN) Already in cart . – musa baltaci Apr 01 '21 at 21:47
  • 1. answer same result it stil shows (NaN) Already in cart . 2. answer doesnot work. – musa baltaci Apr 02 '21 at 07:06
  • Same result, still showing (NaN) Already in cart you can try at this link. http://yeni.hizliveguvenli.com/shop/ – musa baltaci Apr 02 '21 at 07:29