Set maximum combined shipping cost in WooCommerce

This code enables you to set up a maximum combined shipping cost when a customer is ordering a mixture of different products. Add the code to the end of your child themes functions file.

// Custom function to calculate shipping cost
add_filter('woocommerce_package_rates', 'custom_shipping_cost_calculation', 10, 2);
function custom_shipping_cost_calculation($rates, $package) {
    // Set the maximum combined shipping cost
    $max_shipping_cost = 20; // Adjust this value as needed

    // Initialize variables
    $total_shipping_cost = 0;

    // Calculate the total shipping cost for all available shipping methods
    foreach ($rates as $rate_key => $rate) {
        // Ensure we are working with standard shipping methods
        if ($rate->method_id !== 'flat_rate') {
            continue;
        }

        // Add shipping cost to total
        $total_shipping_cost += floatval($rate->cost);
    }

    // Apply the maximum shipping cost if total exceeds the limit
    if ($total_shipping_cost > $max_shipping_cost) {
        foreach ($rates as $rate_key => $rate) {
            // Ensure we are working with standard shipping methods
            if ($rate->method_id !== 'flat_rate') {
                continue;
            }

            // Update the shipping cost to the maximum limit
            $rates[$rate_key]->cost = $max_shipping_cost;
        }
    }

    return $rates;
}

Swap out the value for the $max_shipping_cost variable to set your max shipping cost.

Uses the woocommerce_package_rates filter hook.

Need More Coding Help?

Book a Consultation