Home » Magento

Magento: Create Catalog Price Rule Programmatically

14 June 2011 Share/Bookmark

Here, you will see how to create Catalog Price Rule in Magento through code.

Catalog Rules are applied on products before they are added to the cart.

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

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

Here is the code to create Catalog Price Rule. In this code example, I have created Catalog 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 Fixed Amount Discount To certain amount (in our case: 20) of currency amount

$name = "My Catalog Price Rule"; // name of Catalog Price Rule
$websiteId = 1; 
$customerGroupId = 2; 
$actionType = 'to_fixed'; // discount to fixed amount 
//(other options are: by_fixed, by_percent, to_percent)
$discount = 20; // discount amount
$sku = 'chair'; // product sku

$catalogPriceRule = Mage::getModel('catalogrule/rule');
		
$catalogPriceRule->setName($name)
				 ->setDescription('')
				 ->setIsActive(1)
				 ->setWebsiteIds(array($websiteId))
				 ->setCustomerGroupIds(array($customerGroupId))
				 ->setFromDate('')
				 ->setToDate('')
				 ->setSortOrder('')
				 ->setSimpleAction($actionType)
				 ->setDiscountAmount($discount)
				 ->setStopRulesProcessing(0);
			
$skuCondition = Mage::getModel('catalogrule/rule_condition_product')
					->setType('catalogrule/rule_condition_product')
					->setAttribute('sku')
					->setOperator('==')
					->setValue($sku);
					
try {	
	$catalogPriceRule->getConditions()->addCondition($skuCondition);
	$catalogPriceRule->save();				
	$catalogPriceRule->applyAll();	
} catch (Exception $e) {
	Mage::getSingleton('core/session')->addError(Mage::helper('catalog')->__($e->getMessage()));
	return;
} 

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

Hope this helps. Thanks.

From Mukesh Chapagain's Blog, post Magento: Create Catalog Price Rule Programmatically

email

php magento mukesh chapagain

Get New Post by Email
RSS Feed Subscribe RSS Feed
  • Pravin Agham

    Hi, with your script I successfully created the Catalog price rule in magento but later I found that it doesn’t apply to product.   I have to manually click on “Save and Apply” button and then it get reflect…
    Can you have any idea why this is so..?

    Thanks,
    Pravin

  • Bryan

    you make me happy.  very. very. happy.

  • Chw

    Where do I have to place this code to make it work. Would that work with version 1.5.1.0?
    thanks a lot.