Skip to content

Instantly share code, notes, and snippets.

@drewgillson
Created December 31, 2011 04:35
Show Gist options
  • Save drewgillson/1542893 to your computer and use it in GitHub Desktop.
Save drewgillson/1542893 to your computer and use it in GitHub Desktop.
Magento - apply coupon codes automatically
$productPrice = $_product->getPrice();
$coupon_code = trim(Mage::getSingleton("checkout/session")->getData("coupon_code"));
if ($coupon_code != '') {
/*** Warning - if you choose to use this code, you should probably not
* use the direct SQL query below, and instead use the SalesRule/Rule
* resource collection, which you can access by calling
* Mage::getModel('salesrule/rule')->getResourceCollection()
*
* This example was written a long time ago and the direct SQL query was
* the best I could do given my limited understanding of Magento at the time.
***/
$db = Mage::getSingleton('core/resource')->getConnection('core_read');
$sql = "SELECT discount_amount, conditions_serialized
FROM salesrule_coupon AS a INNER JOIN salesrule AS b ON a.rule_id = b.rule_id
WHERE simple_action = 'by_percent' AND a.code = ?";
$sql = $db->quoteInto($sql, $coupon_code);
$rows = $db->fetchAll($sql);
if (isset($rows[0])) {
$discount = ($rows[0]['discount_amount'] / 100);
/*** This assumes that if there is a shopping cart price rule condition,
* it is a condition with only one parameter - that the product belongs
* to a particular attribute set.
***/
$conditions = unserialize($rows[0]['conditions_serialized']);
$conditions = $conditions['conditions'][0]['conditions'][0];
if (is_array($conditions) && $conditions['value'] == $_product->getAttributeSetId()) {
$productPrice = round($productPrice - ($productPrice * $discount),2);
$sale_price = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment