Menu Close

WooCommerce: Sort Shipping Costs from Low to High

default

A client had several shipping rates on the cart page automatically generated by FedEx, USPS, UPS and similar plugins via their API. Problem was, they wanted to sort them by price as opposed to grouping them by provider.

Thankfully, with a simple “uasort” PHP function, it’s possible to take the shipping rates array and sort it by amount before returning it back to the screen. If you don’t know PHP, simply copy/paste!

Sort shipping costs from low to high in WooCommerce
Sort shipping costs from low to high in WooCommerce

PHP snippet: Sort Shipping Rates by Price @ WooCommerce Cart/Checkout

/**
 * @snippet       Sort Shipping Rates by Price - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter( 'woocommerce_package_rates' , 'businessbloomer_sort_shipping_methods', 9999, 2 );
  
function businessbloomer_sort_shipping_methods( $rates, $package ) {
     
    if ( ! is_array( $rates ) ) return $rates;
   
    uasort( $rates, function ( $a, $b ) { 
        if ( $a == $b ) return 0;
        return ( $a->cost < $b->cost ) ? -1 : 1; 
    } );
   
    return $rates;
  
    // NOTE: BEFORE TESTING EMPTY YOUR CART
      
}
View Source
Posted in WooCommerce Tips