Magento: Create Shopping Cart Price Rule Programmatically

This article will show you how to create shopping cart price rule in Magento through code.

Shopping Cart Price Rules are applied when the customer reaches the shopping cart.

To create a Shopping Cart Price Rule from Admin Panel, we go to Promotions -> Shopping Cart Price Rules and select Add New Rule.

Basically, there are three main parts for Shopping Cart Price Rule, i.e. Rule Information, Conditions, and Actions.

Here is the code to create Shopping Cart Price Rule. In this code example, I have created Shopping Cart Price Rule with the following information:-

– The rule is applied to particular product with the particular SKU (in our case: ‘chair’)
– The rule is applied as Percentage Discount By certain percent (in our case: by 10 percent) of currency amount


$name = "My Shopping Cart Price Rule"; // name of Shopping Cart Price Rule
$websiteId = 1; 
$customerGroupId = 2; 
$actionType = 'by_percent'; // discount by percentage 
(other options are: by_fixed, cart_fixed, buy_x_get_y)
$discount = 10; // percentage discount
$sku = 'chair'; // product sku

$shoppingCartPriceRule = Mage::getModel('salesrule/rule');
		
$shoppingCartPriceRule
	->setName($name)
	->setDescription('')
	->setIsActive(1)
	->setWebsiteIds(array($websiteId))
	->setCustomerGroupIds(array($customerGroupId))
	->setFromDate('')
	->setToDate('')
	->setSortOrder('')
	->setSimpleAction($actionType)
	->setDiscountAmount($discount)
	->setStopRulesProcessing(0);

$skuCondition = Mage::getModel('salesrule/rule_condition_product')
					->setType('salesrule/rule_condition_product')
					->setAttribute('sku')
					->setOperator('==')
					->setValue($sku);
					
try {	
	$shoppingCartPriceRule->getConditions()->addCondition($skuCondition);
	$shoppingCartPriceRule->save();				
	$shoppingCartPriceRule->applyAll();	
} catch (Exception $e) {
	Mage::getSingleton('core/session')->addError(Mage::helper('catalog')->__($e->getMessage()));
	return;
} 

A new Shopping Cart Price Rule with the name “My Shopping Cart Price Rule” has been created. You can view the rule from Promotions -> Shopping Cart Price Rules in admin.

Hope this helps. Thanks.