WooCommerce – How to Show a Confirm Message before Removing an Item from the cart / Update Basket on Quantity Change


A super simple one today, a client requested a popup message to confirm if you want to remove something from the cart. How do we achieve this? Pretty simple really, all you need is a bit of jQuery as shown below:

<code class="language-JS">
&lt;script&gt;

    jQuery( function($) {       
    $('.remove').click( function( event ) {
        if( ! confirm( 'Are you sure you want to remove the product?' ) ) {
            event.preventDefault();
            event.stopPropagation();
        }  

    });
});
&lt;/script&gt;
</code>

Along with this amendment, the client asked if we could automatically update the basket on quantity change… Again, a pretty straightforward task here. In terms of UX, some users seem to find the update cart button as unnecessary or confusing; well, if we can make it easier for the users so the basket updates automatically on change, then why not do it?

ПОЛЕЗНО  Эксперты: Для брутфорс-атак на WordPress используется протокол XMLRPC

A simple PHP function followed by two lines of JQuery and a line of CSS and you can quickly implement this!

1. CSS Snippet: Hide the WooCommerce “Update Cart” Button

<code class="language-CSS">
input[name='update_cart'] {
display: none !important;
}
 
/* SHOULD THAT NOT WORK, TRY THIS */
 
button[name='update_cart'] {
display: none !important;
}
</code>

2. PHP Snippet: Auto-update WooCommerce Cart when Quantity Changes

Now that the update cart button is hidden, all we need to do is to ‘click’ the button via jQuery and let WooCommerce do the exact same job (updating cart totals, taxes, etc.).

In detail, when we ‘click’ on any of the quantity inputs, we go and trigger a ‘click’ on the hidden Update Cart button.

ПОЛЕЗНО  How to Completely Remove Comments From a WordPress Site

Easy, right?

Note: add the following to your functions.php (to the child theme if you using one)

<code class="language-PHP">
add_action( 'wp_footer', 'silva_cart_refresh_update_qty' ); 
 
function silva_cart_refresh_update_qty() { 
   if (is_cart()) { 
      ?&gt; 
      &lt;script type="text/javascript"&gt; 
         jQuery('div.woocommerce').on('click', 'input.qty', function(){ 
            jQuery("[name='update_cart']").click();
         }); 
      &lt;/script&gt; 
      &lt;?php 
   } 
}
</code>