HummingbirdUK main logo

HummingbirdUK

Coding solutions to business problems

About us

We use code to create solutions to business challenges, bottle-necks and headaches.

If you think your business has a problem that can be solved through code, we are happy to chat things through without any obligation.

Get in touch

Delete expired coupons programmatically in Magento

Home / Blog / Delete expired coupons programmatically in Magento

Written by Giles Bennett

A customer the other day installed an extension which then created a fair few unique coupons (in the hundreds), each valid for two days. When the two days had gone, they then wanted to delete expired coupons programmatically. So this is what I came up with for them. In this particular instance there were other expired coupons that they didn't want removed, so we were matching on the first part of the coupon's name, and not just its expiry date.

Delete Expired Coupons Programmatically

As ever, start with the usual : [php] <?php require_once('app/Mage.php'); Mage::app('default'); [/php] Then let's load the coupon collection into $allCoupons and get today's date in Y-m-d format for later use : [php] $allCoupons = Mage::getModel('salesrule/rule')->getCollection()->load(); $rightNow = strtotime('now'); $today = date("Y-m-d", $rightNow); [/php] We then loop through each coupon, get its name, then get the first 16 characters from its name (which is what we're matching on), along with its expiry date in Y-m-d format : [php] foreach ($allCoupons as $aCoupon) { $couponName = $aCoupon->getName(); $subString = substr($couponName,0,16); $expiryDate = $aCoupon->getToDate(); $expiryDay = date("Y-m-d", $expiryDate); [/php] Finally, if the coupon name matches, and the current day is greater than the expiry date, delete the coupon : [php] if(($subString == "Abandoned coupon") && ($today > $expiryDate)) { $aCoupon->delete(); } [/php] And then finish off. [php] } ?> [/php] And that's the lot.
Author : Giles Bennett

About the author

Giles Bennett built his first website in 1996, and is old enough to miss Netscape Navigator. Initially a lawyer, he jumped ship to IT in 2008, and after 5 years as a freelancer, he founded HummingbirdUK in 2013. He can be reached by email at giles@hummingbirduk.com.