2

In certain circumstances, you may want to automatically add a particular shipping rate to an order. For instance, you might want to:

  • use a particular service for estimation purposes
  • force a particular shipping service based on business logic (e.g. it might be free or fixed cost)
  • have the customer skip the shipping pane in checkout
2

You can use Rules for this. You can modify the rule export below and either import it directly into Drupal or include it in MYMODULE.rules_defaults.inc:

/**
 * Implements hook_default_rules_configuration().
 */
function MYMODULE_default_rules_configuration() {
  $configs = array();

  $configs['rules_auto_add_shipping_service'] = rules_import('{ "rules_auto_add_shipping_service" : {
      "LABEL" : "Auto-add shipping service",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "TAGS" : [ "Commerce Shipping" ],
      "REQUIRES" : [ "rules", "commerce_order", "commerce_shipping", "entity" ],
      "ON" : { "commerce_order_update" : [] },
      "IF" : [
        { "data_is" : { "data" : [ "commerce-order:type" ], "value" : "commerce_order" } }
      ],
      "DO" : [
        { "commerce_shipping_delete_shipping_line_items" : { "commerce_order" : [ "commerce_order" ] } },
        { "commerce_shipping_method_collect_rates" : {
            "shipping_method_name" : "flat_rate",
            "commerce_order" : [ "commerce_order" ]
          }
        },
        { "commerce_shipping_rate_apply" : {
            "commerce_order" : [ "commerce_order" ],
            "shipping_service_name" : "standard_shipping"
          }
        }
      ]
    }
  }');

  return $configs;
}

In the example above, the rule fires when an order is updated. When an update occurs it:

  1. Removes all shipping line items from the order. (commerce_shipping_delete_shipping_line_items)
  2. Collects rates for the specified shipping method. You can edit the shipping_method_name from flat_rate to any service you are using (it doesn't have to be Flat Rate).
  3. Applies a particular rate. This rate must be collected during the previous step.

Now, your order will always have a shipping rate applied to it.

To skip checkout, you can disable the shipping pane using the UI or use something like the snippet below to handle it in code:

/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  // No need for shipping since it's auto-selected.
  $checkout_panes['commerce_shipping']['enabled'] = FALSE;
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.