Reputation: 19
I am looking to display the total price of a variable product when multiple quantities are selected. I found this piece of code being suggested in a few different places and it works great for simple products but when used for variable products the 'Product Total' multiplies by the minimum price of the variable product.
For example. We have a variable product with prices that range from $20 - $100
You select a $30 variation, increase the quantity to 2 and the Total Price displays $40.
When added to the cart the Subtotal comes out correct ($60).
How do we get the Total Price line to calculate based on the price of the chosen variation?
Upvotes: 0
Views: 5108
Reputation: 290
try using this code.
<?php
// we are going to hook this on priority 31, so that it would display below add to cart button.
add_action( 'WC_Product_Variable', 'woocommerce_total_product_price', 'set priority here' );
function woocommerce_total_product_price() {
global $woocommerce, $product;
// let's setup our divs
echo sprintf('<div id="product_total_price" style="margin-bottom:20px;display:none">%s %s</div>',__('Product Total:','woocommerce'),'<span class="price">'.$product->get_price().'</span>');
echo sprintf('<div id="cart_total_price" style="margin-bottom:20px;display:none">%s %s</div>',__('Cart Total:','woocommerce'),'<span class="price">'.$product->get_price().'</span>');
?>
<script>
jQuery(function($){
var price = <?php echo $product->get_price(); ?>,
current_cart_total = <?php echo $woocommerce->cart->cart_contents_total; ?>,
currency = '<?php echo get_woocommerce_currency_symbol(); ?>';
$('[name=quantity]').change(function(){
if (!(this.value < 1)) {
var product_total = parseFloat(price * this.value),
cart_total = parseFloat(product_total + current_cart_total);
$('#product_total_price .price').html( currency + product_total.toFixed(2));
$('#cart_total_price .price').html( currency + cart_total.toFixed(2));
}
$('#product_total_price,#cart_total_price').toggle(!(this.value <= 1));
});
});
</script>
<?php
}
?>
Upvotes: 2