更新时间:2023-11-30 16:31:58
以下代码在加载页面时考虑产品数量,然后在更改产品数量时更新价格。
通过代码中添加的注释标签进行解释
function action_woocommerce_single_product_summary() {
global $product;
// Getters
$price = $product->get_price();
$currency_symbol = get_woocommerce_currency_symbol();
// let's setup our div
echo sprintf('<div id="product_total_price" style="margin-bottom:20px;">%s %s</div>', __('Product Total:','woocommerce'), '<span class="price">' . $currency_symbol . $price . '</span>' );
?>
<script>
jQuery(function($) {
// jQuery variables
var price = <?php echo $price; ?>,
currency = '<?php echo $currency_symbol; ?>',
quantity = $( '[name=quantity]' ).val();
// Code to run when the document is ready
var product_total = parseFloat( price * quantity );
$( '#product_total_price .price' ).html( currency + product_total.toFixed( 2 ) );
// On change
$( '[name=quantity]' ).change( function() {
if ( ! ( this.value < 1 ) ) {
product_total = parseFloat( price * this.value );
$( '#product_total_price .price' ).html( currency + product_total.toFixed( 2 ) );
}
});
});
</script>
<?php
}
// We are going to hook this on priority 31, so that it would display below add to cart button.
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 31, 0 );