Magento 2

Magento 2.4 Apply Coupon Code Programmatically

Magento 2

Magento 2.4 Apply Coupon Code Programmatically

In Magento 2, you may come across scenarios where you need to apply a coupon code programmatically during the checkout process. One way to achieve this is by using the Object Manager in your custom code. In this post, we'll guide you through the steps to apply a coupon code programmatically using the Object Manager in Magento 2. Let's dive in!

Note: It's important to note that using the Object Manager directly is not considered a recommended practice in Magento 2. It's preferable to use dependency injection and proper coding standards. However, we'll provide an example using the Object Manager to address your specific request.

Step 1: Accessing the Object Manager To apply a coupon code programmatically, you'll need to access the Object Manager. Here's an example of how you can obtain it in your custom code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

Step 2: Applying the Coupon Code Once you have the Object Manager, you can use it to apply the coupon code programmatically. Follow these steps:

  1. Load the cart session using the Object Manager:
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');

  1. Set the coupon code to be applied:
$couponCode = 'YOUR_COUPON_CODE'; // Replace with the actual coupon code
$cart->getQuote()->setCouponCode($couponCode)->save();

  1. (Optional) If you want to check if the coupon code is valid and applied successfully, you can use the following code snippet:
$coupon = $objectManager->get('\Magento\SalesRule\Model\Coupon');
$coupon->load($couponCode, 'code');
if ($coupon->getId()) {
    // Coupon code is valid and applied
    echo "Coupon code applied successfully!";
} else {
    // Coupon code is not valid or couldn't be applied
    echo "Coupon code is invalid or couldn't be applied.";
}

Step 3: Finalizing the Process After applying the coupon code, you can proceed with the checkout process or perform any additional actions as needed.

Thanks.