我找到了以下代码,该代码根据WooCommerce单个产品的数量计算分类总数:
add_action( 'woocommerce_after_add_to_cart_button', 'bbloomer_product_price_recalculate' );
function bbloomer_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();
" );
}
然而,它仅适用于简单产品,而不适用于可变产品上的产品变体.我需要帮助修改代码,以准确计算变体产品的汇总.
下面,我对代码进行了一些更改,以处理可变产品的选定产品变体:
add_action( 'woocommerce_after_add_to_cart_button', 'bbloomer_product_price_recalculate' );
function bbloomer_product_price_recalculate() {
global $product;
// Check if the product is variable or not
if ( $product->is_type( 'variable' ) ) {
// For variable products, get the default variation price
$default_variation = $product->get_default_attributes();
$variation_id = $product->get_matching_variation( $default_variation );
$variation = wc_get_product( $variation_id );
$price = $variation->get_price();
} else {
// For simple products, get the regular price
$price = $product->get_price();
}
echo '<div id="subtot" style="display:inline-block;">Total: <span></span></div>';
$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();
" );
}
但它不起作用.如何使其也适用于可变产品?