When migrating from another shop or when you have a client who hands you a list of coupon codes, you want to be able to bulk import coupon codes in Magento. Now, there are some existing solutions out there, and I stumbled into this one from Marius Strajeru. This script does generate bulk coupon codes, but with some adjustments I changed the script to a CSV importer for coupon codes.
This example imports a CSV file with coupon codes exported from a ViArt shop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
<?php // Import coupon codes // Thanks go out to Marius Strajeru // Original URL: http://marius-strajeru.blogspot.nl/2010/04/create-bulk-discount-rules.html require 'app/Mage.php'; Mage::app(); // Import CSV from ViArt format: $handle = fopen('coupons.csv', 'r'); $cols = array_flip(fgetcsv($handle)); while($data = fgetcsv($handle)) { if($data[$cols['is_active']] == 1) { echo 'Importing coupon with code: '.$data[$cols['coupon_code']].'<br />'; createCoupon( $data[$cols['coupon_code']], $data[$cols['description']], 'by_fixed', $data[$cols['discount_amount']] ); } else { echo 'Not imported (not active): '.$data[$cols['coupon_code']].'<br />'; } } /** * Import coupon * @param $code String Coupon code * @param $description String Description * @param $type String by_percent, by_fixed, cart_fixed, buy_x_get_y (not implemented) * @param $amount int The amount * @param array $options Optional options (from, to) */ function createCoupon($code, $description, $type, $amount, $options = array()) { // Create coupon: /* @var $rule Mage_SalesRule_Model_Rule */ $rule = Mage::getModel('salesrule/rule'); $rule->setName($code); $rule->setCouponCode($code); $rule->setDescription($description); // Default options: if(!isset($options['from'])) { $options['from'] = date('Y-m-d'); } $rule->setFromDate($options['from']); // From date // To date: if(isset($options['to'])) { $rule->setToDate($options['to']);//if you need an expiration date } $rule->setUsesPerCoupon(1);//number of allowed uses for this coupon $rule->setUsesPerCustomer(1);//number of allowed uses for this coupon for each customer $rule->setCustomerGroupIds(getAllCustomerGroups());//if you want only certain groups replace getAllCustomerGroups() with an array of desired ids $rule->setIsActive(1); $rule->setStopRulesProcessing(0);//set to 1 if you want all other rules after this to not be processed $rule->setIsRss(0);//set to 1 if you want this rule to be public in rss $rule->setIsAdvanced(1);//have no idea what it means :) $rule->setProductIds(''); $rule->setSortOrder(0);// order in which the rules will be applied $rule->setSimpleAction($type); $rule->setDiscountAmount($amount);//the discount amount/percent. if SimpleAction is by_percent this value must be <= 100 $rule->setDiscountQty(0);//Maximum Qty Discount is Applied to $rule->setDiscountStep(0);//used for buy_x_get_y; This is X $rule->setSimpleFreeShipping(0);//set to 1 for Free shipping $rule->setApplyToShipping(1);//set to 0 if you don't want the rule to be applied to shipping $rule->setWebsiteIds(getAllWbsites());//if you want only certain websites replace getAllWbsites() with an array of desired ids $labels = array(); $labels[0] = $description; $rule->setStoreLabels($labels); $rule->setCouponType(2); $rule->save(); } /** * Get all customer groups * @return array */ function getAllCustomerGroups(){ //get all customer groups $customerGroups = Mage::getModel('customer/group')->getCollection(); $groups = array(); foreach ($customerGroups as $group){ $groups[] = $group->getId(); } return $groups; } /** * Get all websites * @return array */ function getAllWbsites(){ //get all wabsites $websites = Mage::getModel('core/website')->getCollection(); $websiteIds = array(); foreach ($websites as $website){ $websiteIds[] = $website->getId(); } return $websiteIds; } |
Just place it with a corresponding CSV-file in the root of your Magento installation and call the URL from your browser. It would be nicer to have this done as an extension, but as a quick fix it will do.
Visitors give this article an average rating of 3.3 out of 5.
How would you rate this article?
★ ★ ★ ★ ★
Thank you very much!! it works like charm!! you save me a lot of time =)
You’re welcome!
Hi there, can you tell me or better give me a sample CSV file to use with this script?
Thanks,
Lar
You saved my life, it works great! Thanks.
By the way, here’s the sample CSV. 1st line is the csv header.
is_active,coupon_code,description,discount_amount,options
1,AABB00001,Cupom 1,100
1,AABB00002,Cupom 2,100
1,AABB00003,Cupom 3,100
1,AABB00004,Cupom 4,100
Where should I place this file and how do I execute it?
Thank you so much it’s really works in magento 1.7 also….
It shows me this Error?
Not imported (not active):
Please explain!
Because in “is_active” cell you put value=0.Just check your “coupons.csv” file and enter value=1 in “is_active” cell.
Thanks…
Nice! works fine thanks
How to use this code?
you saved my life! THANK YOU!
I understand this is quite an old post but i’m struggling to edit this to allow me to set an end date. Any ideas? Great code though thanks! Has helped a lot!
Have you tried
$rule->setFromDate()
and$rule->setToDate()
already? With this you can set a date in YYYY-MM-DD format.Yes sorry I should have included the edits.
I have $rule->setToDate($toDate). And have also included $toDate in my CSV file, and also in the function createCoupon line.
When I run the import with the date in YYYY-MM-DD it results in a date populated with 01/01/1970. I have ready this means it is reading this as empty.
Thank you so much for the quick response! to be honest I wasn’t expecting one because of the date of the post!
When the coupon is saved, is there a value stored in the database (salesrule-table)? Or is it NULL? What happens when you do a
var_dump($rule->debug())
before saving the rule? What’s the value offrom_date
andto_date
then?How can I apply this to a particular product, sku?
Nevermind figured it out. This is the code I used. This codes works pretty much the same for conditions.
$actions = Mage::getModel(‘salesrule/rule_condition_product’)
->setType(‘salesrule/rule_condition_product’)
->setAttribute(‘sku’)
->setOperator(‘==’)
->setValue(‘SCRG-6621’);
$rule->getActions()->addCondition($actions);
Im on magento 1.9 and would love to restrict the codes to specific products – i can’t get your code edit to work. Any ideas?
thx!
The example provided by Crystal should work as intended. All it does is add a condition to your coupon. Didn’t you make any typo’s in the attribute, operator or SKU? Is the rule showing up at all after creating the coupon code?
Will it create a new rule or add codes to current rule?
Hi, this example creates a new rule, but just as with any other Magento model you can load an existing rule by id, modify it and save it.
Thank you for sharing, although I found it’s easier to manage-edit to just use the auto generation feature in Magento http://www.crimsonwing.com/ecommerce/how-to-manage-multiple-coupon-codes-per-shopping-cart-price-rule-in-magento/
Hi, how could i import multiple coupon in a rule?
I’m not sure if I understand your question correctly, but wouldn’t a foreach()-loop do the trick?
hi, may I know where can I use foreach() loop to import multiple coupon codes under one rule?
thanks in advance.
Hi!
I need to create and import 10 000+ coupons for 7 rules. I think it’ll be quite hard and time-consuming. I found this extension to help me https://amasty.com/generate-and-import-coupons.html. Do you have any experience with it? Or do you have any other suggestions?
Thanks in advance
I know there are a lot of extensions to do a lot of stuff. Mostly we tend to use extensions when we want to give our clients the power to do stuff like this themselve. If it’s for a one-timer or very specific task sometimes a shell script is better suited for the task.
Hi
mine is also same requirement can u suggest me if you got the solution.
thanks in advance.
hi thanks for nice code
how do we import multiple coupon codes for a rule. does only foreach work? please suggest me.
Thanks in advance.