WooCommerce: Calculate Subtotal On Quantity Increment @ Single Product

From a UX point of view, ecommerce customers may enjoy a little improvement on the WooCommerce single product page. As soon as they increase the add to cart quantity, it’d be nice if product price could be recalculated or maybe if a “TOTAL” line could appear so that users always know how much they are about to add to cart.

Honestly, this is hard to explain it this way, so the best is if you look at the screenshot. Enjoy!

Product price is $34 and quantity is 10, therefore the “Total” is now $340. Whenever quantity changes, “Total” updates its value.

PHP Snippet: Calculate Total Price Upon Quantity Increment @ WooCommerce Single Product Page

/**
 * @snippet       Calculate Subtotal Based on Quantity - WooCommerce Single Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 4.1
 * @community     https://businessbloomer.com/club/
 */

add_action( 'woocommerce_after_add_to_cart_button', 'bbloomer_product_price_recalculate' );

function bbloomer_product_price_recalculate() {
	global $product;
	echo '<div id="subtot" style="display:inline-block;">Total: <span></span></div>';
	$price = $product->get_price();
	$currency = get_woocommerce_currency_symbol();
	wc_enqueue_js( "		
		$('[name=quantity]').on('input change', function() { 
			var qty = $(this).val();
			var price = '" . esc_js( $price ) . "';
			var price_string = (price*qty).toFixed(2);
			$('#subtot > span').html('" . esc_js( $currency ) . "'+price_string);
		}).change();
	" );
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce Visual Hook Guide: Single Product Page
    Here’s a visual hook guide for the WooCommerce Single Product Page. This is part of my “Visual Hook Guide Series“, through which you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can copy/paste). If you like this guide and it’s helpful to you, let me know in the comments! […]
  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce: Hide Prices on the Shop & Category Pages
    Interesting WooCommerce customization here. A client of mine asked me to hide/remove prices from the shop page and category pages as she wanted to drive more customers to the single product pages (i.e. increasing the click-through rate). As usual, a simple PHP snippet does the trick. I never recommend to use CSS to “hide” prices, […]
  • WooCommerce: Add Custom Field to Product Variations
    Adding and displaying custom fields on WooCommerce products is quite simple. For example, you can add a “RRP/MSRP” field to a product, or maybe use ACF and display its value on the single product page. Easy, yes. Unfortunately, the above only applies to “simple” products without variations (or the parent product if it’s a variable […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent 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. Follow @rmelogli

41 thoughts on “WooCommerce: Calculate Subtotal On Quantity Increment @ Single Product

  1. Hi πŸ™‚
    Thank you for all the tips! not just for this article!
    I’ve adapted your code to mine, to take into account the currency converter plugin I have installed. However, upon page load, the JS script does not run, it only runs and total gets update only if I increase/decrease the qty. Can you please help and tell me what I’m doing wrong?

    Thanks,

    1. Hey Sabine, thanks so much for your comment! Unfortunately this looks like custom troubleshooting work and I cannot help 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

  2. Any chance you can make this work on archive page with quantity selectors?

    1. Hello Majd, 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!

  3. Dear Rudolfo,

    Thanks for your helpful Code. Is it possible to display the regular price along with subtotal as my product is on sale
    would be very thankful if you help me out

    Thanks

    1. Hi Asad 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!

  4. Dear Rudolfo,

    thanks for your helpful Code Snippets. Is it possible to show the subtotal price in another currency format? For example: 15,10 € . The subtotal price is 15 euros and 10 cent.
    We would be very happy if you had an idea. Have an nice day πŸ™‚
    Best regards from Germany Lena

    1. Yes!

      var price_string = (price*qty).toFixed(2).replace(".", ",");
      $('#subtot > span').html(price_string+' " . esc_js( $currency ) . "');
      
      1. Hello and thank you so much
        Please when Im trying to change the two lines in function I got an error could you please type the full code of this

        Thank you again

        1. add_action( 'woocommerce_after_add_to_cart_button', 'bbloomer_product_price_recalculate' );
           
          function bbloomer_product_price_recalculate() {
             global $product;
             echo '<div id="subtot" style="display:inline-block;">Total: <span></span></div>';
             $price = $product->get_price();
             $currency = get_woocommerce_currency_symbol();
             wc_enqueue_js( "      
                $('[name=quantity]').on('input change', function() { 
                   var qty = $(this).val();
                   var price = '" . esc_js( $price ) . "';
                   var price_string = (price*qty).toFixed(2).replace(".", ",");
                   $('#subtot > span').html(price_string+' " . esc_js( $currency ) . "');
                }).change();
             " );
          }
          
  5. Hi,

    Can it be modified to fit the yith dynamic pricing ajax discount?

    To show the total price for each discounted variant quantity, instead of the unit price?

    1. Hi Michael, 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!

  6. Hi Rodolfo.

    This one worked out perfectly.

    I have another query, suppose i have set of products I want to sell and by default I have set quantity as 4. I want the actual product price equal to the default quantity that is set, then later calculate it after the quantity is increased.

    Thankyou

    1. Hi Gaurang, 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!

  7. Calculate Subtotal Based on Quantity – WooCommerce Single Product not working for Variable products ..
    As you can see simple product name – Salted pista Rs 599 Total price is changing on increasing the quantity, on vairable product i.e Dried dates, Its 299- 600 the price is as per the weight , so whenever i’m updating the quantity on different weights, the total amount is still default to the main cost Rs 299, its not changing with the weight price.

    but i think this could be a problem on the grouped products too
    Thanks

    1. That’s possible, probably I only tested it on Simple products

  8. this works, yet, it doesn’t account for the specific variation price, but rather the lowest price possible of the item.
    https://prnt.sc/wl9257

    Do you know how to adjust the code so it adds the specific variation price, and not just the lowest priced variation?

    1. Hello Efrain, 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!

  9. It’s working on my site but it’s not changing the total price when it’s a variable product.

    1. I see, I guess this was coded for simple products only

      1. Hi Rodolfo,
        Please can you change the code for variables products?
        Tks

  10. It works, but does not conform to the currency settings of the site. In Europe decimals are separated with a comma and not a dot.

    1. Yes, you’ll need to adjust the JS to print the format you want

  11. Hello, is it possible to make it work with your custom product qty switchers?
    https://prnt.sc/ukezhu

    1. Hi Vlad, 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!

  12. Great snippet, thanks! Rather than adding the div price subtotal output, I adapted the script to target the class of the existing WC product price so they update when the quantity changes. Worked perfectly πŸ™‚

    1. Nice! Feel free to share

  13. This would be even better and more useful to the customer:

    add_action( 'woocommerce_after_add_to_cart_form', 'bio_product_and_subtotal_on_product_page_on_qty_change' );
    function bio_product_and_subtotal_on_product_page_on_qty_change(){
    global $product;
    $product_price = (float) wc_get_price_to_display($product);
    $cart_subtotal = (float) WC()->cart->subtotal + $product_price;
    $price_0_html = wc_price(0);
    $price_html = '<span class="amount">'.number_format($product_price, 2, ',', ' ').'</span>';
    $subtotal_html = '<span class="amount">'.number_format($cart_subtotal, 2, ',', ' ').'</span>';
    printf('<div id="totals-section"><span class="product-total">Product total: %s</span><br /><span class="cart-subtotal">Cart subtotal: %s</span></div>',
    str_replace([' amount','0,00'], ['',$price_html], $price_0_html),
    str_replace([' amount','0,00'], ['',$subtotal_html], $price_0_html)
    );
    ?>
    <script>
    jQuery( function($){
    var productPrice = <?php echo $product_price; ?>,
    startCartSubtotal = <?php echo $cart_subtotal; ?>;
    function formatNumber(floatNumber){
    return floatNumber.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ').replace('.', ',');
    }
    $('input[name=quantity]').on( 'input change', function(){
    var productQty = $(this).val() == '' ? 1 : $(this).val(),
    productTotal = parseFloat(productPrice * productQty),
    cartSubtotal = productTotal + startCartSubtotal - productPrice;
    cartSubtotal = $(this).val() > 1 ? parseFloat(cartSubtotal) : parseFloat(startCartSubtotal);
    $('#totals-section > .product-total .amount').html( formatNumber(productTotal));
    $('#totals-section > .cart-subtotal .amount').html( formatNumber(cartSubtotal));
    });
    });
    </script>
    <?php
    }
    1. Ok thank you

  14. I think the idea you have put forward is a great improvement but is there any way the code can be changed to work with variations.

    1. Hi Bob, 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!

  15. Hello,
    I thank your blog, it’s super cool.
    I using this code in my site, but de code not function it doesn’t work when I add the product via the ajax add card.
    I think it is the JS that is not being read, can you tell me how I can solve this problem?

    Thank you

    1. Hey Xavier, this is for the single product page, and there is no Ajax there

  16. Hi Rodolfo: I saw this code implemented on a site I visited the other day and thought it was a nice feature to have. So, thanks for sharing this code with us as it is much appreciated! I have already added the code to my dev site.
    -Dave

    1. The only other enhancement I need to make to this code is for Variations. Shouldn’t be pretty easy and straight-forward to add the code.

      1. Awesome!

        1. Hi Dave! Did you figure out how to adapt it for product variations?

          If you did, I’d love to know how you did it. I’m trying to make it work, but it doesn’t seem to be doing it.

          Thanks Rodolfo, great code!

  17. Hey Rodolfo, I agree – this will definitely improve UX. I’ll make sure to use it on my next WooCommerce project. I feel Woo should actually include this functionality in core. Maybe one day. πŸ™‚

    1. Great!

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

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