Magento 2 catalog price rules allow you to create encouraging offers and prompt your customers to finalize the purchase. Unlike cart price rules, catalog rules are applied to the entire catalog, not just the shopping cart.
Traditionally, you create catalog price rules via the admin panel. That's where you specify the rule information and conditions for the discounts to be applied. But you can perform all these steps using coding, too.
So, today you'll learn how to create a catalog price rule in Magento 2 programmatically.
Post Contents [hide]
Create Magento 2 Catalog Price Rule Using Dependency Injection
One of the safest methods to go for is dependency injection. To apply this method, use the code below:
<?php
declare(strict_types=1);
namespace Vendor\Module;
use Magento\CatalogRule\Api\CatalogRuleRepositoryInterface;
use Magento\CatalogRule\Model\RuleFactory;
use Magento\Framework\Exception\CouldNotSaveException;
use Psr\Log\LoggerInterface;
class CreateCatalogPriceRule
{
protected $ruleFactory;
protected $catalogRuleRepository;
protected $logger;
public function __construct(
RuleFactory $ruleFactory,
CatalogRuleRepositoryInterface $catalogRuleRepository,
LoggerInterface $logger
){
$this->ruleFactory = $ruleFactory;
$this->catalogRuleRepository = $catalogRuleRepository;
$this->logger = $logger;
}
public function execute()
{
$rule = $this->ruleFactory->create();
$rule->setName('Programmatic Rule')
->setDescription('Created Programmatically')
->setIsActive(1)
->setCustomerGroupIds([0, 1, 2, 3]) // Assuming these groups exist
->setWebsiteIds([1]) // Assuming this website exists
->setSimpleAction('by_percent')
->setDiscountAmount(10)
->setStopRulesProcessing(0);
// Define conditions here
$conditions = [
'type' => \Magento\CatalogRule\Model\Rule\Condition\Combine::class,
'aggregator' => 'all',
'value' => 1, // 1 means TRUE, i.e., ALL conditions have to be TRUE.
'new_child' => '',
'conditions' => [
[
'type' => \Magento\CatalogRule\Model\Rule\Condition\Product::class,
'attribute' => 'category_ids',
'operator' => '==',
'value' => '10' // Category ID to which the rule applies
]
]
];
$rule->getConditions()->loadArray($conditions);
// Save the rule
try {
$this->catalogRuleRepository->save($rule);
} catch (CouldNotSaveException $e) {
$this->logger->error('This is an error while saving catalogPriceRule');
}
return $rule;
}
}
Create Magento 2 Catalog Price Rule Using Object Manager
Though quite simple at first glance, the object manager can hide the real dependencies of the class. So, we don't recommend to use it directly.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get(Magento\Framework\App\State::class);
$state->setAreaCode('adminhtml');
$ruleFactory = $obj->create(\Magento\CatalogRule\Model\RuleFactory::class);
$catalogRuleRepository = $obj->create(\Magento\CatalogRule\Api\CatalogRuleRepositoryInterface::class);
$rule = $ruleFactory->create();
$rule->setName('Programmatic Rule')
->setDescription('Created Programmatically Object Manager')
->setIsActive(1)
->setCustomerGroupIds([0, 1, 2, 3]) // Assuming these groups exist
->setWebsiteIds([1]) // Assuming this website exists
->setSimpleAction('by_percent')
->setDiscountAmount(10)
->setStopRulesProcessing(0);
// Define conditions here
$conditions = [
'type' => \Magento\CatalogRule\Model\Rule\Condition\Combine::class,
'aggregator' => 'all',
'value' => 1, // 1 means TRUE, i.e., ALL conditions have to be TRUE.
'new_child' => '',
'conditions' => [
[
'type' => \Magento\CatalogRule\Model\Rule\Condition\Product::class,
'attribute' => 'category_ids',
'operator' => '==',
'value' => '10' // Category ID to which the rule applies
]
]
];
$rule->getConditions()->loadArray($conditions);
$catalogRuleRepository->save($rule);
Note: both methods show only one example of the catalog rule. Thus, you can adjust it according to your needs to determine any specific conditions.
Here you go! Now you have two more methods at hand and can create catalog price rules programmatically in Magento. These rules together with other discounts can help you launch successful and efficient campaigns.