为小计设置$ 110以下的零税-Woocommerce

时间:2019-06-12 02:25:56

标签: wordpress woocommerce hook-woocommerce

我正在尝试为低于$ 110 的订单设置免税

我碰到了这个线程Set different Tax rates conditionally based on cart item prices in Woocommerce并尝试了它,但是当我将它添加到functions.php上时似乎不起作用-也许是因为某些代码已经过时了?

这是修改后的代码:

add_action( 'woocommerce_before_calculate_totals', 'change_cart_items_prices', 10, 1 );
function change_cart_items_prices( $cart ) {

  if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

  if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
    return;

foreach ( $cart->get_cart() as $cart_item ) {
    // get product price
    $price = $cart_item['data']->get_price();

    // Set conditionaly based on price the tax class
    if ( $price < 111 )
        $cart_item['data']->set_tax_class( 'zero-rate' ); // below 111
    if ( $price >= 111 )
        $cart_item['data']->set_tax_class( 'standard' ); // Equal above 110
  }
}

我相信Woo Commerce>“设置”>“税”中的“标准和零税率”税选项设置正确。

1 个答案:

答案 0 :(得分:0)

使用以下代码使其正常工作:

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;

$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 ) {
    $cart_item['data']->set_tax_class( 'zero-rate' );
}
}