【问题标题】:Set zero taxes when total cart value before taxes is lower than a set amount - woocommerce当税前购物车总价值低于设定金额时设置零税 - woocommerce
【发布时间】:2021-11-16 18:22:06
【问题描述】:

我一直在阅读这篇文章Set 'Zero Tax' for subtotal under $110 - Woocommerce 作为参考,以在购物车总价值

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;

     if ( WC()->customer->get_shipping_country() !== 'US' )
        return;

         $defined_amount = 800;
         $subtotal = 0;

        foreach ( $cart->get_cart() as $cart_item ) {
        $subtotal += $cart_item['line_total'];
        }

        if ( $subtotal < $defined_amount )
        return;

        foreach ( $cart->get_cart() as $cart_item ) {
        $cart_item['data']->set_tax_class( 'zero' );
        }
}

【问题讨论】:

  • 我没有立即在您的代码中看到错误。您是否已调试以有效了解小计值?您是否正在使用其他可能会产生影响的自定义代码或插件?
  • @7uc1f3r - 感谢您检查我的代码。我测试它的方法是设置 $defined_amount = 0 和 $subtotal = 10。然后我将以下条件 if ($subtotal = $defined_amount) 设置到代码中,它返回“零”税级。所以我假设循环已经用零覆盖了 10 的初始 $subtotal 值。当我设置条件 if ($subtotal > $defined_amount) 时,选择了“其他”税类。
  • 如果您通过将 $subtotal 设置为 10 来测试这一点,那么即使执行循环,10 也永远不会被 0 覆盖。因为在循环中 line_total 被添加到 $subtotal 所以它只能是 10 或超过 10。正如我所提到的,debugging 似乎是解决问题的唯一正确方法
  • 这确实很有帮助。谢谢您的建议。马努

标签: php woocommerce checkout subtotal tax


【解决方案1】:

调试后,下面编辑的代码对我有用:

add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_zero_tax_rate', 10, 1 );

function apply_conditionally_zero_tax_rate( $cart ) {
     

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

    if ( WC()->customer->get_shipping_country() !== 'US' )
        return;
  

    $defined_amount = 800;
    $subtotal = 0;

  
    foreach ( $cart->get_cart() as $cart_item ) {
    $subtotal += $cart_item['line_total'];
    }
       

    if ( $subtotal > $defined_amount ){

      foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
      $cart_item['data']->set_tax_class( 'zero' );
      }
    }  
}

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 2014-04-19
    • 1970-01-01
    • 2013-10-25
    • 2021-05-28
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多