Generating Magento Discount Coupons from Code
The admin is fine for the odd coupon, but campaigns, loyalty schemes and integrations often need codes created automatically. In Magento 1 you can build the whole shopping cart price rule in PHP.
The code
This creates a rule with a fixed coupon code. Adjust the discount type, amount, customer groups, websites and dates to suit:
<?php
/**
* Create Shopping Cart Sales Rule with Specific Coupon Code Programmatically
*/
// All customer group ids
$customerGroupIds = Mage::getModel('customer/group')->getCollection()->getAllIds();
// SalesRule Rule model
$rule = Mage::getModel('salesrule/rule');
// Rule data
$rule->setName('Rule name')
->setDescription('Rule description')
->setFromDate('')
->setCouponType(Mage_SalesRule_Model_Rule::COUPON_TYPE_SPECIFIC)
->setCouponCode('my-coupon-code')
->setUsesPerCustomer(1)
->setUsesPerCoupon(1)
->setCustomerGroupIds($customerGroupIds)
->setIsActive(1)
->setConditionsSerialized('')
->setActionsSerialized('')
->setStopRulesProcessing(0)
->setIsAdvanced(1)
->setProductIds('')
->setSortOrder(0)
->setSimpleAction(Mage_SalesRule_Model_Rule::BY_FIXED_ACTION)
->setDiscountAmount(10)
->setDiscountQty(1)
->setDiscountStep(0)
->setSimpleFreeShipping('0')
->setApplyToShipping('0')
->setIsRss(0)
->setWebsiteIds(array(1))
->setStoreLabels(array('My Rule Frontend Label'));
// Product found condition type
$productFoundCondition = Mage::getModel('salesrule/rule_condition_product_found')
->setType('salesrule/rule_condition_product_found')
->setValue(1) // 0 == not found, 1 == found
->setAggregator('all'); // match all conditions
// 'Attribute set id 1' product condition
$attributeSetCondition = Mage::getModel('salesrule/rule_condition_product')
->setType('salesrule/rule_condition_product')
->setAttribute('manufacturer')
->setOperator('==')
->setValue(10);
// Bind attribute set condition to product found condition
$productFoundCondition->addCondition($attributeSetCondition);
// If a product with 'attribute set id 1' is found in the cart
$rule->getConditions()->addCondition($productFoundCondition);
// Only apply the rule discount to this specific product
$rule->getActions()->addCondition($attributeSetCondition);
// Here we go
$rule->save();
For thousands of unique codes, use the rule’s auto-generation feature instead of creating one rule per code.
Heads up: this guide applies to Magento 1, which stopped receiving official security updates in June 2020. If your store still runs it, plan a move to Magento 2 or Adobe Commerce soon. We can help with the migration.
Want this done for you? Find out more about our Magento development service.