Getting the coupon code from the order in Magento
· One min read
This article will show how to get the coupon code from the order.
First, we will get the order by id using the OrderRepository class. Using the OrderRepository is the best current practice for loading the order by ID in Magento 2.
Code for getting the coupon code from the order
You can use the following code snippet anywhere in your code to obtain the coupon code from the order.
<?php
namespace Mexbs\SomePlugin;
class SomeClass
{
protected $orderRepository;
public function __construct(
\Magento\Sales\Model\OrderRepository $orderRepository
) {
$this->orderRepository = $orderRepository;
}
public function someFunction()
{
$orderId = 3;
$order = $this->orderRepository->get($orderId);
$couponCode = $order->getCouponCode();
//...do something
}
}
To sum up
In this article, we showed how to get the coupon code from the order after loading the order by id.
info
This code was tested on Magento CE 2.4.7-p3