WooCommerce: Automatically Update Cart on Quantity Change

There is a lot of literature online that solves this UX problem – so in this article let’s see if I can give you a simplified, working, updated version.

So, do you hate the “Update Cart” button too? Yes, the one you have to click after you update the quantity of a product in the cart…

Well, you’re in the right place: a simple PHP function, two lines of JQuery, one line of CSS and the result is pretty straight forward!

Automatically update the WooCommerce Cart when the quantity changes

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

First of all we need to hide the button, as we’re not going to use it at all and let PHP and JQuery do the magic instead. I know !important is not a great thing to have in your CSS code… but for this time we’ll keep it simple.


input[name='update_cart'] {
display: none !important;
}

/* OR TRY THIS */

button[name='update_cart'] {
display: none !important;
}

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

Now that the 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.

Easy, no?


/**
 * @snippet       Automatically Update Cart on Quantity Change - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=73470
 * @author        Rodolfo Melogli
 * @compatible    Woo 3.5.1
 */

add_action( 'wp_footer', 'bbloomer_cart_refresh_update_qty' ); 

function bbloomer_cart_refresh_update_qty() { 
	if (is_cart()) { 
		?> 
		<script type="text/javascript"> 
			jQuery('div.woocommerce').on('click', 'input.qty', function(){ 
				jQuery("[name='update_cart']").trigger("click"); 
			}); 
		</script> 
		<?php 
	} 
}

Where to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (before "?>" if you have it). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7+.

If you think this code saved you time & money, please join other Business Bloomer supporters and avail of 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce Customization?

Check out these free video tutorials. You can start learning how to customize WooCommerce without unnecessary plugins. Watch me code and learn by example!

  • how-to-edit-woocommerce-with-php-snippets
  • woocommerce-hooks-add_action-list-visual
  • woocommerce-customize-single-product-page-PHP

Rodolfo Melogli

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as a WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza.

72 thoughts on “WooCommerce: Automatically Update Cart on Quantity Change

  1. Fantastic solution. Thank you for this. What would be the way to have an Ajax quantity and Add to cart on a single product page?

    1. Tamas, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  2. Hi, Rodolfo!
    This snippet is perfect for UX, but with cart and checkout on one page from your blog (https://businessbloomer.com/woocommerce-cart-checkout-same-page/) didn’t working.

    1. Yes I guess this needs to be customized for this edge case.

  3. Hi! It did not work on mine. I can hide the button but the script isn’t working.

    1. Hello Ana, it could be your server (outdated jQuery) or the fact you’re using a custom theme. Do any other snippet work?

  4. It worked on the desktop version, but as soon as I try to add more quantity on my phone version, it just says, updating and nothing happens.

    1. Hi Azam, thanks for your comment! I just tested this again with Storefront theme and it works perfectly. Maybe your theme (or another plugin) is messing/conflicting with my snippet?

      To troubleshoot, disable all plugins but WooCommerce and also switch temporarily to “Twentyseventeen” theme (load the snippet there in functions.php) – does it work? If yes, you have a problem with your current theme or one of the plugins.

      Hope this helps!

      R

    2. Hello Rodolfo, I’m a big fan of this website and your snippets can really save the day! This one is a great piece of code to start with, but triggering Ajax call every time quantity increases is poor design.

      I created free plugin Ajax Cart AutoUpdate to address this and many more issues:
      https://wordpress.org/plugins/ajax-cart-autoupdate-for-woocommerce/

      It works with WooCommerce 2.6+ (requires WordPress 4.4+), because it’s the version which introduced Ajax cart in core and allows to use built-in update event.

      To start with, you properly mentioned both CSS rules, as version 3.4.0 of WooCommerce changed Update cart from input to button type. It’s even cleaner to use the following, as .button class of this element is used across all versions:

      .button[name='update_cart']{
      display: none!important;
      } 

      In my code Ajax calls aren’t constantly sent due to introduced update delay, in provided example it’s 1000 miliseconds, but actual plugin uses value specified in settings. It works like this:

      “Cart update is delayed by amount in miliseconds since last action affecting quantity, specified by user in settings, default 1000. It means that update will fire only once, when user is done with changes.”

      Also for page speed fanatics, remember that if you want to defer jQuery, you better load scripts using wp_enqueue_script, with jQuery dependency set, because inline script with jQuery will fail in such case.

      var timeout;
      
      jQuery('div.woocommerce').on('change keyup mouseup', 'input.qty', function(){ // keyup and mouseup for Firefox support
          if (timeout != undefined) clearTimeout(timeout); //cancel previously scheduled event
          if (jQuery(this).val() == '') return; //qty empty, instead of removing item from cart, do nothing
          timeout = setTimeout(function() {
              jQuery('[name="update_cart"]').trigger('click');
          }, 1000 ); // schedule update cart event with 1000 miliseconds delay
      });
      

      I read about problems with Update button disabled causing updates to fail, but I couldn’t reproduce it on any WooCommerce version, Storefront and other themes, so in my code I don’t try to handle it.

      1. Fantastic!

      2. This is awesome!

        One small issue. If the quantity is already minimum and you try to decrease further, even if the values don’t change, it still refreshes again. How can you modify this code to filter this out?

  5. Am on 3.6.1 woocommerce, php 7.3, and the latest WP.

    The snippet is not functioning currently.

    1. Hello Jason, thanks for your comment! I just tested this again with Storefront theme and it works perfectly. Maybe your theme (or another plugin) is messing/conflicting with my snippet?

      To troubleshoot, disable all plugins but WooCommerce and also switch temporarily to “Twentyseventeen” theme (load the snippet there in functions.php) – does it work? If yes, you have a problem with your current theme or one of the plugins.

      Hope this helps!

      R

  6. Hello, i got a question about this snippet, Is there a way the cart wouldn’t update if i’ve applied one of your another snippet (change quantity to dropdown -> https://businessbloomer.com/woocommerce-change-add-cart-quantity-drop/) ?

    Beceause i’ve tried your snippet and the one of Jos with the ‘change’ but it seems not to update. Any clue if it is linked or it should be another “input” ?

    Thanks a lot for your content !

    1. Hey Dario, thanks for your comment! Yes, that’s likely the reason why. Unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  7. Hi,
    I need the cart to update when an item goes out of stock. Is there an easy variation of your code that will do this?

    Basically, my customers like to add items to their cart and then come back a few days later to purchase. Because we sell plants of limited quantities they can run out of stock before they buy.

    I have managed to get a message to show up, telling them the item has gone out of stock and they need to update their cart but often they seem to ignore the message, so I want the cart to update itself as well.

    Appreciate any help you can offer.
    Thank you

    1. Hello Bryan, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  8. Hi again Rodolfo.
    Once again thx for your help.

    As i mentioned to you earlier. Your code above does not work for quantity with +/- selectors.
    However, a little twist will also make your code work for that as well:

    add_action( 'wp_footer', 'bbloomer_cart_refresh_update_qty' );
    
    function bbloomer_cart_refresh_update_qty() {
        if (is_cart()) {
            ?>
            
            jQuery('div.woocommerce').on('change', 'input.qty', function(){
                setTimeout(function() {
                    jQuery('[name="update_cart"]').trigger('click');
                }, 100 );
            });
            
            <?php
        }
    }
    
    1. Nice, thank you πŸ™‚

    2. Syntaxe error any idea

      1. Try now πŸ™‚

  9. cool snippet Rodolfo.
    However, this only works when actually clicking inside the quantity input. I can’t make it work when clicking the decrease or increase (+/-) signs.

  10. Another CSS code to hide button that works with my theme:

    button[name=”update_cart”] {
    display: none !important;
    }

    1. Thank you πŸ™‚

  11. Your solution didnt work( even gave a 500 error) But JOS’s solution from july is perfect. Please update it

  12. Hi,
    Thanks for the code, works nicely, with one caveat. css snippet has input[name=’update_cart’] but in my case (version 3.5.1) it works with button[name=’update_cart’]
    Take care
    Can

    1. Thanks!

  13. This code really helpful for me thanks.

    1. Nice πŸ™‚

  14. Great code!

    I need to set it to another class, but then it only works once. How come? And how to fix that?

     
    jQuery('.woocommerce-cart-form').on('change', 'input.qty', function(){ 
    

    Thanks!

    1. Hey Peps – thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  15. Hi.

    It’s an useful topic for me as I am creating an eCommerce Store. I am using ‘WHOLESALE MARKET’ Plugin from “Cedcommerce”. As per your Instant Price Update, I want to update the price instantly when the quantity reaches its Minimum Order of quantity. It can not update for each increament of quantity as you said. So can you give me what code and where should i insert?

    1. Hello Jonn, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  16. Hey, your code did not work for me πŸ™ This one, instead, works like a charm (found on stack exchange)

    add_action( 'wp_footer', 'cart_update_qty_script' );
    function cart_update_qty_script() {
        if (is_cart()) :
            ?&gt;
            
        jQuery('div.woocommerce').on('change', '.qty', function(){
        jQuery("[name='update_cart']").prop("disabled", false);
            jQuery("[name='update_cart']").trigger("click"); 
        });
        
            &lt;?php
        endif;
    }
    
    1. Thanks Cam πŸ™‚

  17. If I may suggest an update, if you set a timeout variable it doesn’t jump on every click. Example:

    
    add_action( 'wp_footer', 'bbloomer_cart_refresh_update_qty' ); 
    
    function bbloomer_cart_refresh_update_qty() { 
    	if (is_cart()) { 
    		?&gt; 
         
          var timeout;
    			jQuery('div.woocommerce').on('click', 'input.qty', function(){ 
            if(timeout != undefined){
              clearTimeout(timeout);
            }
            timeout = setTimeout(function() {
              jQuery("[name='update_cart']").trigger("click"); 
            }, 500);
    			}); 
    		 
    		&lt;?php 
    	} 
    }
    
    
    1. Very nice, thanks a lot MartΓ­ πŸ™‚

    2. I made some changes:
      – Update after 2 seconds (our customers aren’t faster than that πŸ™‚ )
      – Update on changes with keyboard as well
      – Don’t update if the value is empty

      add_action( 'woocommerce_after_cart', function() {
      	?>
      		<script>
      			jQuery(function($) {
      				var timeout;
      				$('div.woocommerce').on('change textInput input', 'form.woocommerce-cart-form input.qty', function(){
      					if(typeof timeout !== undefined) clearTimeout(timeout);
      
      					//Not if empty
      					if ($(this).val() == '') return;
      
      					timeout = setTimeout(function() {
      						$("[name='update_cart']").trigger("click"); 
      					}, 2000);
      				}); 
      			});
      		</script>
      	<?php
      } );
      
      1. AWESOME! Thanks Jos πŸ™‚

  18. Hi, nice trick, very helpful for me, but I found two issues and solved it as follows:
    —> replace input[name=’update_cart’] to: button[name=’update_cart’];
    —> button[name=’update_cart’] is disabled by default and it is necessary to enable it when window is loaded and cart is updated:

    jQuery(window).on('load', function(){
        jQuery("[name='update_cart']").removeAttr('disabled');
    });
    jQuery( document.body ).on( 'updated_cart_totals', function(){
        jQuery("[name='update_cart']").removeAttr('disabled');
    );
    
    1. Thanks Agata, I’d say this is very much theme-dependent. Cheers πŸ™‚

  19. Hello need add setTimeout to correct work with all themes http://prntscr.com/jsiy12

    1. Nice tip, let’s see if it helps anyone. Thanks πŸ™‚

    2. This worked for me, thank you @Wayheming and @Rodolfo!

      1. πŸ™‚

  20. Did not work on the cart page, works on the Single product page.

    1. Sorry, the hide did not work. Rest of it worked.

      1. Thanks Ibrahim! You might have to change the input name the JQuery targets, take a look πŸ™‚

  21. Hi Rodolfo,
    Great snippet, works like a charm on pc!
    Is it also supposed to work on mobile, or it is only me?
    My theme is storefront.
    Many thanks!

    1. Hey Kostas, thanks for your message! It should work well on mobile as well, however I did not test it. It could be that the CSS classes and HTML tags I target in the PHP change for mobiles, so the code *might* need to be adjusted. Give it another go and let me know

  22. After latest WordPress 4.9.6 and WooCommerce 3.4 update I get a tooltip notice on Chrome “Please match the format requested” http://prntscr.com/jm3t18 and it doesn’t work

    1. Hey Michal, thanks for your comment! I just tested this again with Storefront theme and it works perfectly. Maybe your theme (or another plugin) is messing/conflicting with my snippet?

      To troubleshoot, go to WP Dashboard > WooCommerce > System Status: what errors do you see in red font?

      Also, take a look at this tutorial to see how to troubleshoot: https://businessbloomer.com/woocommerce-troubleshooting-mistakes-to-avoid/

      Finally, can you try switching temporarily to “Twentyseventeen” or “Storefront” theme and let me know if it works?

      Hope this helps!

      R

  23. The only addendum I’d like to add is for theme individuality…

    Some themes only have a button to update the cart, so, a little editing of the css is helpful:

    /** hide update cart button if function used */
    input[name=’update_cart’], button[name=’update_cart’] {
    display: none !important;
    }

    this will hide either/or both the input, and a buuton if used by a theme.

    1. Cool thanks Roberta πŸ™‚

  24. Hi, this works well, only I need the plus & minus buttons also update the cart in the same way it does when inputting the number in the box. Would it be possible?

    Many thanks πŸ™‚

    1. Arus, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  25. This snippet is ideal for me but any idea why it would only work on every second change?

    1. Naomi, thanks for your comment! Uhm, no idea, maybe there is a jQuery conflict specific to your theme/plugins πŸ™‚

    2. I have the same issue. I am using Flatsome theme. Is there a way to troubleshoot jQuery conflicts?

      1. Hey Sanya / Naomi! If the Jquery works on another theme such as 2017, then there is a problem with Flatsome (bug). In this case, it might be worth it contacting their support team πŸ™‚

    3. It’s because the β€œupdate cart” button is disabled at the beginning, only when input is changed then it becomes active.
      Add one line and it should work πŸ™‚

      jQuery(‘div.woocommerce’).on(‘change’, ‘input.custom-qty’, function(){
      jQuery(“[name=’update_cart’]”).removeAttr(‘disabled’);
      jQuery(“[name=’update_cart’]”).trigger(“click”);
      });

      @rodolfo please ignore my previous comments and leave only that one πŸ˜‰

    4. Maybe an onChange event, to the qty field would work – so if a user uses either the plus & minus buttons, or types in an quantity amount change, it responds to the event?

  26. Hello Rodolfo,
    First of all, nice snippets, very helpful.
    I’m living near Valencia, Spain, so have a nice tryp over there.
    I just wanted to say that I’ve tried this snippet, but it doesn’t works.
    Maybe it’s because of the new update of woocommerce.
    Thank you again.

    1. Thank you Stan! Could you try the snippet on a different theme please e.g. 2017?

  27. Hello Rodolfo.

    First of all thank you for the idea. It works as expected. The only problem I see with it, is that when you click on the normal “Update Cart” button, there goes a whole process that takes a second or two. The same happens with the JQuery snippet you included and of course, it is expected, as it is only clicking for us. But if the customer has many different items in cart and wish to edit the whole order before checking out, he or she will find him or her self waiting on each number changed until quantities are as expected. On the old fashion way (button), you change all the numbers you want to and then the button is clicked and you only wait once.

    Nothing wrong with your snippet, in fact, it is an excellent idea for stores that mostly sell one or few items and there will always be only one or a few items in a cart at the same time. The problem is that WooCommerce lacks simplicity in the amount updating routine, like for example, when I shop in AliExpress, you pick an item, click on “+” or “-” symbol in “Quantity” and the dollars amount is updated instantly. Not even the waiting symbol shows. Maybe WooCommerce looks at too many things at the same time when cart is updated, like tax, availability, etc. etc., which introduces the a lag in the output.

    Thanks again for all your simple, but helpful and brilliant ideas.

    Richard

    1. Thanks for your comment Richard! I’m sure WooCommerce is looking into this for future developments πŸ™‚

  28. Suggestion.

    Changing this line:

    jQuery('div.woocommerce').on('click', 'input.qty', function(){

    to:

    jQuery('div.woocommerce').on('change', 'input.qty', function(){

    will still allow updating the quantity via keyboard.

    1. @Metal Guru no you need to wait every time from changing for example from 5 to 1

  29. That’s a very clever solution. I was expecting you to disable the “Update Cart” button via a template change and then trigger the ajax call to update the cart.

Questions? Feedback? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between: [php]code_here[/php]. Failure to complying with this (as well as going off topic) will result in comment deletion. You should expect a reply in about a week - this is a popular blog but I need to get paid work done first. Please consider joining #BloomerArmada to ask me 1-to-1 WooCommerce questions. Thank you :)

Your email address will not be published. Required fields are marked *