Calculate Subtotal On Quantity Increment @ Single Product

woocommerce single product calculate subtotal quantity

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!

woocommerce single product calculate subtotal quantity 1
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
 * @author        PHP - Stackoverflow
 * @compatible    WooCommerce 4.1
 */

add_action( 'woocommerce_after_add_to_cart_button', 'phpsof_product_price_recalculate' );

function phpsof_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 (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, feel free to join 10,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 Customization?

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

Leave a Reply

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