Print Commerce shipping service label/title from Order in Message

Public

Commerce Message cannot get Shipping service label/title from Order. This is how to create your own token !order-shipping and add it into your message body.

Notice that this method works for other line items too... Also, it works for other modules that send emails (such as commerce_email) but with some difference in the hook function - currently hook_message_presave($message) -.

Credits to this issue: http://drupalcommerce.org/node/10096

</> CopyGet raw version
php
  1. // Set arguments for our custom token !order-shipping
  2. function MYMODULE_message_presave($message) {
  3. if (!empty($message->mid)) {
  4. return;
  5. }
  6. $message->arguments['!order-shipping'] = array(
  7. 'callback' => 'commerce_message_order_shipping',
  8. 'pass message' => TRUE,
  9. );
  10. }
  11.  
  12. /**
  13.  * Message callback; Show Order Shipping Service label (!order-shipping).
  14.  *
  15.  * @param $message
  16.  * The Message entity.
  17.  */
  18. function commerce_message_order_shipping(Message $message) {
  19. $wrapper = entity_metadata_wrapper('message', $message);
  20. // Get order id from current commerce message
  21. $order_id = $wrapper->message_commerce_order->getIdentifier();
  22. // Get order from order_id
  23. $order_wrapper = commerce_order_load($order_id);
  24. // Get the line items. Shipping service is a line item (like product, discount etc)
  25. $line_items = $order_wrapper->commerce_line_items['und'];
  26.  
  27. // Loop through the line items so you find the shipping service
  28. foreach ($line_items as $delta => $line_item_wrapper) {
  29. $line_item_id = $line_item_wrapper['line_item_id'];
  30. $line_item = commerce_line_item_load($line_item_id);
  31. //dpm($line_item);
  32. if(isset($line_item->commerce_shipping_service)) {
  33. // This is want we need, the shipping service label
  34. $shipping_service = $line_item->line_item_label;
  35. }
  36. }
  37.  
  38. return $shipping_service;
  39. }