59
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!
PHP snippet: Sort Shipping Rates by Price @ WooCommerce Cart/Checkout
/**
* @snippet Sort Shipping Rates by Price - WooCommerce
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible Woo 3.8
* @donate $9 https://tutoraspire.com
*/
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 cost ) ? -1 : 1;
} );
return $rates;
// NOTE: BEFORE TESTING EMPTY YOUR CART
}