我正在尝试按数量更新各个 WooCommerce 产品的页面小计。我通过以下 URL 找到了一个非常适合简单产品的解决方案:https://medium.com/@xemoro/how-to-display-the-calculated-subtotal-based-on-quantity-in-woocommerce-单变量产品-24379410a227.
简单的产品代码如下:
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', 'calculate_product_subtotal' );
function calculate_product_subtotal() {
global $product;
if ( $product->is_type( 'variable' ) ) {
$default_attributes = $product->get_default_attributes();
$variation_id = $product->get_matching_variation( $default_attributes );
$variation = wc_get_product( $variation_id );
$price = $variation->get_price();
} else {
$price = $product->get_price();
}
echo '<div id="subtot" style="display:inline-block;">Total: <span></span></div>';
$currency = get_woocommerce_currency_symbol();
wc_enqueue_js( "
jQuery('[name=quantity]').on('input change', function() {
var qty = jQuery(this).val();
var price = '" . esc_js( $price ) . "';
var price_string = (price * qty).toFixed(2);
jQuery('#subtot > span').html('" . esc_js( $currency ) . "' + price_string);
}).change();
" );
}
但是,可变的产品代码给我的网站带来了严重错误,内容如下:
Deprecated: Function WC_Product::get_matching_variation is deprecated since version 3.0! Use Product data store find_matching_product_variation instead.
当我尝试用“find_matching_product_variation”更新“get_matching_variation”时,我收到另一个严重错误,内容如下:
Fatal error: Uncaught Error: Call to undefined method WC_Product_Variable::find_matching_product_variation()
谢谢大家的帮助。
回答了我的问题。将以下代码片段添加到functions.php中对于可变产品非常有效:
function action_woocommerce_after_add_to_cart_button() {
global $product;
echo '<div id="subtot" style="display:inline-block;"><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);
// Greater than
if ( qty > 1 ) {
$( '#subtot > span').html( 'Total: " . esc_js( $currency ) . "' + price_string );
} else {
$( '#subtot > span').html( '' );
}
}).change();
" );
}
add_action( 'woocommerce_after_add_to_cart_button'
action_woocommerce_after_add_to_cart_button', 10, 0 );`