Magento 2 Automatically change price rules
For our latest Magento 2 project we had to create a price rule that is only active on one day of the week at a special time. Magento is not able to do such special price rule tasks. I show you how you can do that and explain how it works.
Magento 2 Automatically change price rules
If you want to change a Magento 2 price rule programmatically, you can use this code:
1 2 3 4 5 6 7 8 9 | //change price rule $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $catalogPriceRule = $objectManager->get('Magento\CatalogRule\Model\Rule')->load(1); $catalogPriceRule->setIsActive($state); $catalogPriceRule->save(); //apply all catalog rules $ruleJob = $objectManager->get('Magento\CatalogRule\Model\Rule\Job'); $ruleJob->applyAll(); |
First we get the specific price rule by code. For our project it was easy to set the correct id for this price rule, because it was the only one assigned. For better usability of this code you should get the price rule by name. Our rule was initially deactivated, so our cron job task activates this rule by setting the state. The correct state for an active price rule is 1, 0 means deactivated. To reuse this code, I did that change by a variable called $state.
Setting the state is only one part. You also have to apply all price rules with applyAll() method. This is the same logic as you may have noticed in Magento backend. You can edit rules as you wish, only after applying all rules, they are computed in frontend. Be aware of that – this is a common mistake in working with Magento price rules!
Automatically tasks
If you want to run this changes automatically on a specific time, you have to build a simple Magento 2 module and add this into a cron job method. There you should get the current time and do you tasks based on this information. For our project that automatically change of price rules runs without problems.
Price Rules
You can find edit price rules in Magento 2 under Marketing -> Catalog Price Rules. There you have a grid view with all price rules for this shop. As you can see, you can save and apply rules by simply clicking a button. Don’t forget to do the same if you create od change price rules programmatically.
Conclusion
With Magento 2 it is possible to change price rules programmatically with you own module and do this changes by cron jobs.