B-219 Sec-55 Noida, India
+918010221733

Magento: Create Catalog Price Rule Programmatically

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.

(Visited 880 times, 1 visits today)

Leave a reply

You must be logged in to post a comment.