Search code examples
wordpresswoocommerceproducthook-woocommerce

"WC()->cart->get_subtotal()" returns 0 when using "woocommerce_product_get_tax_class" hook


I'm trying to drop the VAT on my cart items when the subtotal is over a specific amount. But when I use WC()->cart->get_subtotal() to get the subtotal price, it returns 0 and my if statement fails.

add_action( 'woocommerce_product_get_tax_class', 'wp_check_uk_vat', 1, 2 );
    
function wp_check_uk_vat( $tax_class, $product ) {

    $cart_total = WC()->cart->get_subtotal();
    // echo $cart_total;

    if( $cart_total >= 100 ) {

        $tax_class = "Zero rate";

    }

    return $tax_class;

}

Similar code is used here: https://docs.woocommerce.com/document/setting-up-taxes-in-woocommerce/#section-18

The goal of the code is to drop the VAT on the cart (not shipping) when the order amount is over 135 GBP (to comply with the new Brexit rules for merchants).

Because WC()->cart->get_subtotal() returns 0, the if statement fails, and the VAT is not being dropped.


Solution

  • Try this

    add_action( 'woocommerce_product_get_tax_class', 'wp_check_uk_vat', 1, 2 );
    
    function wp_check_uk_vat( $tax_class, $product ) {
    
        if(WC()->cart){
        $subtotal = 0;
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            $subtotal += $cart_item[ 'data' ]->get_price( 'edit' ) * $cart_item[ 'quantity' ];
        }
    
        if ( $subtotal >= 100 ) {
    
            $tax_class = "Zero rate";
        }
        }
        return $tax_class;
    }