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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

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 this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (delete "?>" if you have it there). 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.3.

If you think this code saved you time & money, feel free to join 14,000+ WooCommerce Weekly subscribers for blog post updates or 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

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.

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

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

  2. 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();
             " );
          }
          
  3. 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!

  4. 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!

  5. 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

  6. 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!

  7. 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

  8. 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

  9. 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!

  10. 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

  11. 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

  12. 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!

  13. 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

  14. 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!

  15. 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? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. 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 BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

Your email address will not be published.