Search code examples
woocommerceshipping-method

How to get the lowest FLAT RATE shipping cost in WooCommerce


What I want is simple: I want to display the lowest flat rate shipping cost on a product page in WooCommerce so I can display: "We already deliver orders from € ...".

It doesn't matter what shipping zone of customer country is active... I just need the overall (static) lowest flat rate cost available.

So far I have this:

foreach ((array) $delivery_zones as $key => $delivery_zone ) {

    $shipping_costs = [];

    foreach ($delivery_zone['shipping_methods'] as $value) {
        $shipping_costs[] = $value->cost;
        break;
    }

    echo (min($shipping_costs));
}                           

But this still outputs ALL the flat rate costs f.i.: 1,99 3,99 5,99

How can I only display the lowest (in this case 1,99) rate?

Many tnx!


Solution

  • I think it is a simple mistake, please try this:

    function get_lowest_shipping_flat_rate_1()
    {
        $delivery_zones = WC_Shipping_Zones::get_zones(); 
    
        //define the array outside of the loop
        $shipping_costs = [];
        $min_zone = "";
    
        //get all costs in a loop and store them in the array
        foreach ((array) $delivery_zones as $key => $the_zone ) {
    
        foreach ($the_zone['shipping_methods'] as $value) {
            $shipping_costs[] = $value->cost;
            if(min($shipping_costs) == $value->cost) $min_zone = $the_zone['zone_name'];
            }
        }
    
        $content = $min_zone . " - " . get_woocommerce_currency_symbol() . " " . min($shipping_costs);
    
        return $content;
    }