HummingbirdUK main logo

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 Magento coupons automatically

Home / Blog / Delete expired Magento coupons automatically

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.

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.

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.