Question

I need to create a page which lists all special products (with active special price). How can I do this?

Was it helpful?

Solution

This is how I did it

    $objectManager   = \Magento\Framework\App\ObjectManager::getInstance();

    $visibleProducts = $objectManager->create('\Magento\Catalog\Model\Product\Visibility')->getVisibleInCatalogIds();
    $collection = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\Collection')->setVisibility($visibleProducts);

    $collection = $this->_addProductAttributesAndPrices($collection);

    $stockFilter = $objectManager->create('\Magento\CatalogInventory\Helper\Stock');
    $stockFilter->addInStockFilterToCollection($collection);

    $collection    
        ->addAttributeToFilter(
            'special_price',
            ['gt'=>0], 'left'
        )->addAttributeToFilter(
            'special_from_date',['or' => [ 0 => ['date' => true, 
                                                'to' => date('Y-m-d',time()).' 23:59:59'],
                                          1 => ['is' => new \Zend_Db_Expr(
                                             'null'
                                         )],]], 'left'
        )->addAttributeToFilter(
            'special_to_date',  ['or' => [ 0 => ['date' => true,
                                               'from' => date('Y-m-d',time()).' 00:00:00'],
                                         1 => ['is' => new \Zend_Db_Expr(
                                             'null'
                                         )],]], 'left'
        );

OTHER TIPS

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */
        $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');    

        $min =10; $max =1000;

        $productCollection->addFieldToFilter('special_price', ['lt' => $min, 'gt' => $max]);

        $productCollection->load();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top