Drupal 8 Commerce add promotion programmatically to the order or shopping cart

Posted on 29/06/2020

Doing this for a particular order is pretty straightforward. All you need to have is the coupon code ID:

  1. // This is the ID of the coupon code you want to add to the order.
  2. $coupon_id = 1;
  3.  
  4. /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
  5. $order = \Drupal\commerce_order\Entity\Order::load(1);
  6. $order->get('coupons')->appendItem($coupon_id);
  7. $order->save();

Doing this for the shopping cart involves a bit more boilerplate code to set things up:

  1. // This is the ID of the coupon code you want to add to the order.
  2. $coupon_id = 1;
  3.  
  4. /** @var \Drupal\commerce_cart\CartManager $cart_manager */
  5. $cart_manager = \Drupal::service('commerce_cart.cart_manager');
  6.  
  7. /** @var \Drupal\commerce_cart\CartProvider $cart_provider */
  8. $cart_provider = \Drupal::service('commerce_cart.cart_provider');
  9.  
  10. /** @var \Drupal\commerce_store\Entity\Store $store */
  11. $store = \Drupal::service('commerce_store.current_store')->getStore();
  12.  
  13. /** @var \Drupal\commerce_order\Entity\OrderInterface $cart */
  14. $cart = $cart_provider->getCart('default', $store);
  15.  
  16. // Finally, add the coupon and save changes in the order.
  17. $cart->get('coupons')->appendItem($coupon_id);
  18. $cart->save();