The code given below reorders WooCommerce shipping methods, arranges the rates from low to high order cost, and also ensures that free shipping methods are displayed at the end in the sorted shipping options.
add_filter( 'woocommerce_package_rates' , 'ts_sort_shipping_method_by_cost_zero_empty_cost_last', 10, 2 ); function ts_sort_shipping_method_by_cost_zero_empty_cost_last( $rates, $package ) { if ( empty( $rates ) || ! is_array( $rates ) ) return; // Sort shipping methods based on cost uasort( $rates, function ( $a, $b ) { if ( $a == $b ) return 0; return ( $a->cost < $b->cost ) ? -1 : 1; } ); $free = $zero = []; // Initializing // Loop through shipping rates foreach ( $rates as $rate_key => $rate ) { // For "free shipping" methods if ( 'free_shipping' === $rate->method_id ) { // set them on a separated array $free[$rate_key] = $rate; // Remove "Free shipping" method from $rates array unset($rates[$rate_key]); } // For other shipping rates with zero cost elseif ( $rate->cost == 0 ) { // set them on a separated array $zero[$rate_key] = $rate; // Remove the current method from $rates array unset($rates[$rate_key]); } } // Merge zero cost and "free shipping" methods at the end if they exist return ! empty( $free ) || ! empty( $zero ) ? array_merge($rates, $zero, $free) : $rates; }
Output
Here is the output of the sorted shipping options arranged from low to high cost, followed by free or zero-cost options always at the end of the list.
The below output shows that the default options of how it was arranged before applying the code.
You can also try to clearly show the shipping costs as ‘0’ for free shipping methods. Look into our post that will help you to display $0.00 amount for free shipping rates in WooCommerce.