Delete expired coupons programmatically in Magento

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 
require_once('app/Mage.php');
Mage::app('default');

Then let’s load the coupon collection into $allCoupons and get today’s date in Y-m-d format for later use :

$allCoupons = Mage::getModel('salesrule/rule')->getCollection()->load();
$rightNow = strtotime('now');
$today = date("Y-m-d", $rightNow);

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 :

foreach ($allCoupons as $aCoupon) {
	$couponName = $aCoupon->getName();
	$subString = substr($couponName,0,16);
	$expiryDate = $aCoupon->getToDate();
	$expiryDay = date("Y-m-d", $expiryDate);

Finally, if the coupon name matches, and the current day is greater than the expiry date, delete the coupon :

	if(($subString == "Abandoned coupon") && ($today > $expiryDate)) { 
		$aCoupon->delete();
	}

And then finish off.

}

?>

And that’s the lot.