Kategorier
WooCommerce WordPress

WooCommerce: Sort shipping rates by cost

This goes into your functions.php

/**
 * Sort shipping rates by cost
 * (Automatically select the cheapest price as default)
 *
 * @param array $packages
 * @return array
 */
add_filter('woocommerce_shipping_packages', 'my_woocommerce_shipping_packages_sort_by_cost', 100);
function my_woocommerce_shipping_packages_sort_by_cost($packages)
{
    foreach ($packages as $index => $package) {
        if (!empty($package['rates']) && is_array($package['rates']) && count($package['rates']) > 1) {
            // sort rate by cost
            $rates = $package['rates'];
            usort($rates, function ($a, $b) {
                return $a->cost > $b->cost ? 1 : -1;
            });

            // restore key/value pair
            $_rates = [];
            foreach ($rates as $rate) {
                $_rates[$rate->get_id()] = $rate;
            }

            // override with sorted rates
            $packages[$index]['rates'] = $_rates;
        }
    }

    return $packages;
}