questions

Set all shipping methods costs to zero based on cart items subtotal in WooCommerce

Rate this post

i have multiple shipping methods on my page and want to make them cost zero when the order is above 2500 Czech crowns. I only found the code to only show the Free shipping option when the customer hits the minimum for free shipping but that is not what I want.. I want to show all the methods (but with zero price) so customer still can choose which shipping company he wants his order to be delivered with. Thank you!

 

✔️Solution:

Based on Set cart shipping total amount issue after Woocommerce update answer code, here is the way to make it work based on specific cart items subtotal amount:

add_filter('woocommerce_package_rates', 'null_shipping_costs_conditionally', 10, 2 );
function null_shipping_costs_conditionally( $rates, $package ){
    $threshold_amount = 2500;
    
    if( $package['contents_cost'] >= $threshold_amount ) {
        // Loop through shipping methods rates
        foreach ( $rates as $rate_key => $rate ){
            // Targeting all shipping methods except "Free shipping"
            if ( 'free_shipping' !== $rate->method_id ) {
                $has_taxes = false;
                $taxes = [];
    
                $rates[$rate_key]->cost = 0; // Set cost to 0 (zero)
                // Taxes rate cost (if enabled)
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $tax > 0 ){
                        $has_taxes = true;
                        $taxes[$key] = 0; // Set tax cost to 0 (zero)
                    }
                }
                if( $has_taxes )
                    $rates[$rate_key]->taxes = $taxes;
            }
        }
    }
    return $rates;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Note: After saving this code, don’t forget to empty your cart to refresh shipping cached data.

Leave a Reply

Your email address will not be published.

Back to top button