这个想法很简单。在WooCommerce产品页面上,当客户更改数量时,显示产品总计(价格上涨或下跌)和购物车小计。
我现在被困住了。即使打开调试,我也没有任何错误。产品页面上没有任何显示。
add_action( 'woocommerce_after_add_to_cart_form', 'total_product_and_subotal_price' );
function total_product_and_subotal_price() {
global $product;
// the div section
echo sprintf('',__('Product Total:','woocommerce'),''.$product->get_price().'');
echo sprintf('',__('Cart Total:','woocommerce'),''.$product->get_price().'');
?>
<script>
jQuery(function($){
var price = get_price(); ?>,
current_cart_total = cart->cart_contents_total; ?>,
currency = '';
$('[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
}
您的代码中有一些错误,请尝试以下将动态显示的错误:
基于您的代码:
add_action( 'woocommerce_after_add_to_cart_form', 'total_product_and_subotal_price' );
function total_product_and_subotal_price() {
global $product;
$product_price = (float) wc_get_price_to_display( $product );
$cart_subtotal = (float) WC()->cart->subtotal + $product_price;
$currency_symbol = get_woocommerce_currency_symbol();
$html = '<div id="totals-section">';
$html .= sprintf( '%s%s %s%s',
'<p class="product-total"><span class="woocommerce-Price-amount">',
__('Product Total:','woocommerce'),
'<span class="woocommerce-Price-currencySymbol">'.$currency_symbol.'</span>',
'<span class="amount">'.number_format($product_price, 2).'</span></span></p>'
);
$html .= sprintf( '%s%s %s%s',
'<p class="cart-subtotal"><span class="woocommerce-Price-amount">',
__('Cart Total:','woocommerce'),
'<span class="woocommerce-Price-currencySymbol">'.$currency_symbol.'</span>',
'<span class="amount">'.number_format($cart_subtotal, 2).'</span></span></p>'
);
// Display formatted product price total and cart subtotal amounts
echo $html.'</div>';
?>
<script>
jQuery( function($){
var productPrice = <?php echo $product_price; ?>,
startCartSubtotal = <?php echo $cart_subtotal; ?>;
$('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);
$('div#totals-section .product-total span .amount').html(productTotal.toFixed(2));
$('#totals-section .cart-subtotal span .amount').html(cartSubtotal.toFixed(2));
});
});
</script>
<?php
}
代码进入您的活动子主题(或活动主题)的functions.php文件中。经过测试和工作。