当购物车中有特定产品 ID 时,我尝试更改 WooCommerce 中的税率。我发现 将小计设置为“零税”低于 110 美元 - Woocommerce 答案代码并且有效。我只是不知道如何修改它来检查购物车中的产品 ID。
如果小计金额低于 110 美元,以下将为特定产品设置“零税”:
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_zero_tax_rate', 10, 1 );
function apply_conditionally_zero_tax_rate( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$targeted_product_ids = array(37, 53); // Here define your specific products
$defined_amount = 110;
$subtotal = 0;
// Loop through cart items (1st loop - get cart subtotal)
foreach ( $cart->get_cart() as $cart_item ) {
$subtotal += $cart_item['line_total'];
}
// Targeting cart subtotal up to the "defined amount"
if ( $subtotal > $defined_amount )
return;
// Loop through cart items (2nd loop - Change tax rate)
foreach ( $cart->get_cart() as $cart_item ) {
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$cart_item['data']->set_tax_class( 'zero-rate' );
}
}
}
或者,当购物车中有任何特定产品且小计低于 110 美元时,以下将设置“零税”:
add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_zero_tax_rate', 10, 1 );
function apply_conditionally_zero_tax_rate( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$targeted_product_ids = array(37, 53); // Here define your specific products
$defined_amount = 110;
$subtotal = 0;
$found = false;
// Loop through cart items (1st loop - get cart subtotal)
foreach ( $cart->get_cart() as $cart_item ) {
$subtotal += $cart_item['line_total'];
if( in_array( $cart_item['product_id'], $targeted_product_ids ) ) {
$found = true;
}
}
// Targeting cart subtotal up to the "defined amount"
if ( ! ( $subtotal <= $defined_amount && $found ) )
return;
// Loop through cart items (2nd loop - Change tax rate)
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_tax_class( 'zero-rate' );
}
}