DRUPAL COMMERCE: ADD PROMOTION/DISCOUNT FROM CODE

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

// This is the ID of the coupon code you want to add to the order.
$coupon_id = 1;

/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = \Drupal\commerce_order\Entity\Order::load(1);
$order->get('coupons')->appendItem($coupon_id);
$order->save();

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

// This is the ID of the coupon code you want to add to the order.
$coupon_id = 1;

/** @var \Drupal\commerce_cart\CartManager $cart_manager */
$cart_manager = \Drupal::service('commerce_cart.cart_manager');

/** @var \Drupal\commerce_cart\CartProvider $cart_provider */
$cart_provider = \Drupal::service('commerce_cart.cart_provider');

/** @var \Drupal\commerce_store\Entity\Store $store */
$store = \Drupal::service('commerce_store.current_store')->getStore();

/** @var \Drupal\commerce_order\Entity\OrderInterface $cart */
$cart = $cart_provider->getCart('default', $store);

// Finally, add the coupon and save changes in the order.
$cart->get('coupons')->appendItem($coupon_id);
$cart->save();

Need a Drupal Expert?

Senior Drupal developer, freelance, specialized in what's hardest: migrations, multilingual sites, SaaS platforms and Stripe integration. I leverage AI to cut delivery times and costs, with expert review on every line of code.

No agency, no middlemen. Direct contact with the one who does the work.