Menu Close
    Hire Us Request Quote Reading List Switch to Dark Mode

    Product collection which satisfies catalog rule in magento2

    In Magento2, 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.

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

     

    Hope this functionality helps you to implement functionality in magento2.

     

    Thank you.

    . . .

    Comment

    Add Your Comment

    Be the first to comment.

    Back to Top
    css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close