Search code examples
phpwordpresswoocommercediscount

Percentage discount on shipping based on order total in WooCommerce


I'm trying to find a way through a plugin or via functions.php on how to discount the shipping only by 50% if the order is between £25 and £50.

I am using "Set a percentage discount to Local pickup shipping method in Woocommerce " which discounts based on shipping method but I want it to discount all shipping methods as we have many and it doesn't have a rule for minimum order.


Solution

    • You could use the woocommerce_package_rates hook

    • This will give a discount to the shipping by 50% if the order is between £25 and £50.

    function filter_woocommerce_package_rates( $rates, $package ) {
        /* Settings */
        $min = 25;
        $max = 50;
        $discount_percent = 50;
    
        // Get cart total
        $cart_total = WC()->cart->cart_contents_total;
    
        // Condition
        if ( $cart_total >= $min && $cart_total <= $max ) {
            // (Multiple)
            foreach ( $rates as $rate_key => $rate ) {
                // Get rate cost            
                $cost = $rates[$rate_key]->cost;
                
                // Set rate cost
                $rates[$rate_key]->cost = $cost - ( ( $cost * $discount_percent ) / 100 );
            }
        }
    
        return $rates;
    }
    add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );