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 WooCommerceSort 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    Woo 3.8
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter( 'woocommerce_package_rates' , 'businessbloomer_sort_shipping_methods', 10, 2 );
  
function businessbloomer_sort_shipping_methods( $rates, $package ) {
   
    if ( empty( $rates ) ) return;
  
    if ( ! is_array( $rates ) ) return;
   
    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
      
}
Share:

Leave a Reply