0

I want to calculate tax based on the entire cart subtotals. So in my case, if the subtotal is < 1000, the Tax need to be 5% If the subtotal is >=1000, the Tax needs to be 12%

I am having two classes Reduced rate - 5%, Standard - 12%

    add_action( 'woocommerce_product_variation_get_tax_class', 'wp_check_gst', 1, 2 );
    function wp_check_gst( $tax_class, $product ) 
    {
    
            $subtotal = 0;
            foreach ( WC()->cart->get_cart() as $cart_item ) {
                    $subtotal += $cart_item[ 'data' ]->get_price( 'edit' ) * $cart_item[ 'quantity' ];
                    
            }
            if ( $subtotal >= 1000 )
            {
                $tax_class = "Standard";
            }
            if ( $subtotal < 1000 )
            {
                $tax_class = "Reduced rate";
            }
        return $tax_class;
    }

I use this above code, which seems to be not working?? What am I missing?

Radogost
  • 143
  • 5
  • 16
musthafa
  • 433
  • 8
  • 21

1 Answers1

1

The hook you are using is not the appropriate for the job. Since you want to modify the tax class which affects the basket totals you must use the hook woocommerce_before_calculate_totals. Your code should be like this:

add_action( 'woocommerce_before_calculate_totals', 'tax_based_on_cart_subtotal', 10, 1 );
function tax_based_on_cart_subtotal( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

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

    //Standard Tax 12%
    if ( $subtotal > 1000  ){
       // Change tax class for each cart ietm
       foreach ( $cart->get_cart() as $cart_item ) {
          $cart_item['data']->set_tax_class( 'standard' );
       }
    }

    //Reduced rate Tax 5%
    if ( $subtotal < 1000  ){
       // Change tax class for each cart ietm
       foreach ( $cart->get_cart() as $cart_item ) {
          $cart_item['data']->set_tax_class( 'reduced rate' );
       }
    }
}
Barnabas
  • 139
  • 10
  • 1
    $subtotal = 0; foreach ( $cart->get_cart() as $cart_item ) { $subtotal += $cart_item['line_total']; }.... I need to add this to make it to work – musthafa Jun 17 '22 at 04:45
  • @musthafa thanks, changed the answer above. I'll test also my previous answer a bit better and come back if there is a way to make it work. – Barnabas Jun 18 '22 at 11:05