Reading list Switch to dark mode

    Product collection which satisfies Catalog Rule in Magento 2

    Updated 2 January 2023

    In Magento 2, if you are adding a functionality in which you want to get product’s collection or product ids which satisfies the catalog rules, then you can use the gives code:

    public function getCatalogPriceRuleProductIds()
    {
        $storeManager = \Magento\Framework\App\ObjectManager::getInstance()->create(
             '\Magento\Store\Model\StoreManagerInterface'
        );
        $catalogRule = \Magento\Framework\App\ObjectManager::getInstance()->create(
             '\Magento\CatalogRule\Model\RuleFactory'
        );
        
        $websiteId = $storeManager->getStore()->getWebsiteId();//current Website Id
    
        $resultProductIds = [];
        $catalogRuleCollection = $catalogRule->create()->getCollection();
        $catalogRuleCollection->addIsActiveFilter(1);//filter for active rules only
        foreach ($catalogRuleCollection as $catalogRule) {
            $productIdsAccToRule = $catalogRule->getMatchingProductIds();
            foreach ($productIdsAccToRule as $productId => $ruleProductArray) {
                if (!empty($ruleProductArray[$websiteId])) {
                    $resultProductIds[$productId] = $catalogRule->getName();//name of rule
                }
            }
        }
        return $resultProductIds;
    }
    

    Here,

    $storeManager, is an object of StoreManagerInterface.

    $catalogRule, is an object of CatalogRule collection.

    getMatchingProductIds(), it return the all product ids which are used in conditions according to websites, and assign 1 for the product ids which satisfies the condition.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    $resultProductIds, returns an array in which product ids are as keys and catalog rule’s name is an value.

    I hope this blog will help you with Product collection which satisfies Catalog Rule in Magento 2. You may also check our wide range of best Magento 2 Extensions.

    Please reach out to our team via a support ticket if you have any queries.

    Try this and if you have any queries then just comment below 🙂

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home