Jeremi Liwanag
Jeremi Liwanag

Reputation: 964

Set 'Zero Tax' for subtotal under $110 - Woocommerce

I'm trying to setup no tax for orders under $110.

I bumped into this thread Set different Tax rates conditionally based on cart item prices in Woocommerce and tried it but doesn't seems to work when i add it on functions.php - Maybe because some of the codes are outdated?

Here's the revised code:

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
  }
}

I believe Standard & Zero rates tax options in Woo commerce > Settings > Tax are setup correctly.

Upvotes: 0

Views: 919

Answers (1)

Jeremi Liwanag
Jeremi Liwanag

Reputation: 964

Got it working using this code:

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' );
    }
}

Upvotes: 1

Related Questions