Search code examples
phpwordpresswoocommercecartshipping-method

Include taxes when editing programmatically WooCommerce taxable shipping rates


I am programmatically editing the shipping rates based on Cart Total with the code bellow:

function wc_ninja_change_flat_rates_cost($rates, $package)
{
    if (isset($rates['flat_rate:2'])) {
        $cart_subtotal = WC()->cart->cart_contents_total;
        if ($cart_subtotal >= 60) {
            $rates['flat_rate:2']->cost = 0;
            $rates['flat_rate:2']->label = __('Next Day - Free Delivery', 'woocommerce');
        }
    }
    return $rates;
}
add_filter('woocommerce_package_rates', 'wc_ninja_change_flat_rates_cost', 10, 2);

All works fine but tax is still being added to the orders.

How can I make these flat rate shipping methods taxable whilst changing their values?


Solution

  • Just add a line to set the taxes to zero. You can do it like this:

    add_filter('woocommerce_package_rates', 'wc_ninja_change_flat_rates_cost', 10, 2);
    function wc_ninja_change_flat_rates_cost( $rates, $package ) {
        if ( isset( $rates['flat_rate:1'] ) ) {
            $cart_subtotal = WC()->cart->cart_contents_total;
            if ( $cart_subtotal >= 60 ) {
                $rates['flat_rate:1']->cost = 0;
                $rates['flat_rate:1']->label = __('Next Day - Free Delivery', 'woocommerce');
                // set the tax amount to zero
                $rates['flat_rate:1']->taxes = 0;
            }
        }
        return $rates;
    }
    

    You can find more information in this answer: Set specific taxable shipping rate cost to 0 based on cart subtotal in WooCommerce

    The code has been tested and works. Add it to your active theme's functions.php.