Magento 2: Create and apply catalog price rule programmatically to streamline your store’s promotional strategies. This process involves defining the catalog price rule, setting its conditions and actions, and saving it to the database. Follow this step-by-step guide to implement the functionality efficiently and boost your e-commerce store’s performance.
Magento 2: Create and apply catalog price rule programmatically
1. Define the Catalog Price Rule
The catalog price rule requires conditions (filters for which products it applies to) and actions (the discount logic).
2. Code to Create and Apply the Rule
You can create a custom script (standalone PHP script or a module) to implement the following logic:
Example Script: Create and Apply Catalog Price Rule
use Magento\Framework\App\Bootstrap;
use Magento\CatalogRule\Model\RuleFactory;
use Magento\CatalogRule\Model\ResourceModel\Rule as RuleResource;
use Magento\Framework\App\State;
use Magento\CatalogRule\Model\Indexer\Indexer;
use Magento\CatalogRule\Model\Rule\Job;
// Initialize Magento Bootstrap
require __DIR__ . './app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
// Set Area Code
$state = $obj->get(State::class);
$state->setAreaCode('adminhtml');
// Get Rule Factory and Resource
$ruleFactory = $obj->get(RuleFactory::class);
$ruleResource = $obj->get(RuleResource::class);
// Create New Rule
/** @var \Magento\CatalogRule\Model\Rule $rule */
$rule = $ruleFactory->create();
// Define Rule Data
$rule->setName('Programmatic Discount Rule') // Rule Name
->setDescription('10% off on products priced above $100') // Description
->setIsActive(1) // Active
->setWebsiteIds([1]) // Website IDs (e.g., Default Website ID = 1)
->setCustomerGroupIds([0, 1, 2, 3]) // Customer Groups (e.g., General, Wholesale)
->setFromDate(date('Y-m-d')) // Start Date
->setToDate('2025-01-31') // End Date
->setSortOrder(1); // Sort Order
// Define Rule Conditions (Applies to products priced > $100)
$conditions = [
'type' => 'Magento\CatalogRule\Model\Rule\Condition\Combine',
'aggregator' => 'all',
'value' => 1,
'conditions' => [
[
'type' => 'Magento\CatalogRule\Model\Rule\Condition\Product',
'attribute' => 'price',
'operator' => '>=',
'value' => 100
]
]
];
$rule->setConditionsSerialized(json_encode($conditions));
// Define Rule Actions (10% discount)
$rule->setSimpleAction('by_percent') // Discount Type: 'by_percent' for percentage discount
->setDiscountAmount(10); // Discount Value: 10%
// Save the Rule
$ruleResource->save($rule);
// Apply All Rules
$job = $obj->get(Job::class);
$job->applyAll();
echo "Catalog price rule created and applied successfully.\n";
3. Explanation of Key Fields
Field | Description |
---|---|
setName() | Sets the name of the catalog price rule. |
setDescription() | Provides a description for the rule. |
setIsActive() | Enables or disables the rule (1 = active, 0 = inactive). |
setWebsiteIds() | Specifies the website(s) where the rule applies (use the website IDs). |
setCustomerGroupIds() | Defines which customer groups the rule applies to. |
setFromDate() | Start date for the rule. |
setToDate() | End date for the rule. |
setSimpleAction() | Type of discount (by_percent , by_fixed , to_percent , to_fixed ). |
setDiscountAmount() | Value of the discount (e.g., 10 for 10% or $10 depending on the type). |
setConditionsSerialized() | JSON-encoded conditions defining the applicability of the rule. |
4. Verify and Test
Verify in Admin Panel:
Navigate to Marketing > Catalog Price Rules in the Magento admin panel to confirm the rule creation.
Reindex and Clear Cache:
After applying the rule, ensure the rule is reflected across the store by reindexing and clearing the cache:
php bin/magento indexer:reindex
php bin/magento cache:flush
- Test on Frontend:
Add products matching the rule conditions to your cart and check if the discount is applied correctly.
Notes on Create and apply catalog price rule programmatically
Dynamic Updates: If the conditions of the catalog price rule are frequently updated, ensure that re-indexing occurs programmatically. Debugging: Check logs (var/log/system.log
and var/log/exception.log
) if the rule doesn’t apply as expected.Custom Conditions: For more complex conditions, consider extending Magneto’s conditions framework.
Watch our technical vlogs – https://sbdevblog.com/sb-dev-blog-is-now-on-youtube/