Here’s a step-by-step guide to creating Magento 2 coupon codes programmatically:
- Create a New Coupon Rule: To create a new coupon rule programmatically, you need to first create a new instance of the
\Magento\SalesRule\Model\Ruleclass. You can do this using the Magento 2 Object Manager or dependency injection.
$rule = $this->_objectManager->create(Rule::class);
- Set the Rule Information: Once you have created a new instance of the
Ruleclass, you need to set the rule information, such as the rule name, description, and discount amount. You can do this using the
$rule->setName('10% Off Your Order');
$rule->setDescription('Get 10% off your order with this coupon code');
- Set the Coupon Code Information: After setting the rule information, you need to set the coupon code information, such as the code itself, usage limit, and expiration date.
$couponCode = 'NEWCUSTOMER10'; // Replace with your desired coupon code
$rule->setToDate(date('Y-m-d', strtotime('+1 week')));
- Set the Conditions: Next, you need to set the conditions that must be met for the coupon code to apply. You can do this using the
setConditionsmethod and passing in an instance of the
$conditions = [
'type' => 'Magento\SalesRule\Model\Rule\Condition\Address',
'attribute' => 'shipping_method',
'operator' => '==',
'value' => 'flatrate_flatrate',
- Save the Rule: Finally, you need to save the rule using the
That’s it! By following these steps, you can create a new coupon code programmatically in Magento 2. You can customize the coupon code information and conditions to fit your specific needs.