当选择多个数量时,我希望显示可变产品的总价。我发现这段代码在几个不同的地方被建议使用,它适用于简单的产品,但当用于可变产品时,"产品总额"乘以可变产品的最低价格。
例如。我们有一种可变的产品,价格从20美元到100美元不等
您选择一个30美元的变体,将数量增加到2,总价显示为40美元。
当添加到购物车时,小计显示正确(60美元)。
我们如何根据所选变化的价格来计算总价线?
尝试使用此代码。
<?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
}
?>