Skip to content

Instantly share code, notes, and snippets.

@drewgillson
Created December 31, 2011 03:18
Show Gist options
  • Save drewgillson/1542684 to your computer and use it in GitHub Desktop.
Save drewgillson/1542684 to your computer and use it in GitHub Desktop.
Magento - apply coupon code automatically
public function indexAction() {
$coupon_code = $this->getRequest()->getParam('coupon_code');
if ($coupon_code != '') {
Mage::getSingleton("checkout/session")->setData("coupon_code",$coupon_code);
Mage::getSingleton('checkout/cart')->getQuote()->setCouponCode($coupon_code)->save();
Mage::getSingleton('core/session')->addSuccess($this->__('Coupon was automatically applied'));
}
else {
Mage::getSingleton("checkout/session")->setData("coupon_code","");
$cart = Mage::getSingleton('checkout/cart');
foreach( Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item ) {
$cart->removeItem( $item->getId() );
}
$cart->save();
}
if ($this->getRequest()->getParam('url')) {
//using raw header instead of _redirect because _redirect appends a /
header('HTTP/1.1 301 Moved Permanently');
$gclid = this->getRequest()->getParam('gclid');
$url = $this->getRequest()->getParam('url');
header('Location: /' . $url . '?gclid=' . $gclid);
die();
} else {
$this->_redirect("/");
}
}
@baleinen
Copy link

This took me too long on a Sunday

$gclid = this->getRequest()->getParam('gclid');

should be

$gclid = $this->getRequest()->getParam('gclid');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment