Sort Commerce Shipping services by price versus providers.

Public

Sorts Drupal Commerce shipping methods by price

</> CopyGet raw version
php
  1. <?php
  2.  
  3. /**
  4.  * Implements hook_commerce_shipping_service_rate_options_alter().
  5.  */
  6. function mymodule_commerce_shipping_service_rate_options_alter(&$options, $order) {
  7. // If there is more than one shipping service available, sort them by line item unit price
  8. if (count($order->shipping_rates) > 1) {
  9. // Collect rates from line items
  10. $service_prices = array();
  11. foreach ($order->shipping_rates as $service => $line_item) {
  12. $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
  13. $unit_price = $line_item_wrapper->commerce_unit_price->value();
  14. $service_prices[$service] = $unit_price['amount'];
  15. }
  16.  
  17. // array_multisort can be used here because $options and $order->shipping_rates contain the same number of elements (i.e. services).
  18. array_multisort($service_prices, SORT_NUMERIC, SORT_ASC, $options);
  19. }
  20. }