【问题标题】:WooCommerce: Change tax rate when specific products are in cartWooCommerce:当特定产品在购物车中时更改税率
【发布时间】:2021-05-28 05:18:51
【问题描述】:
【问题讨论】:
标签:
php
wordpress
woocommerce
cart
tax
【解决方案1】:
如果小计低于 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' );
}
}