0

Is there anyway to display best seller products by date range? For example recent last 7 days or recent 30 days or recent 60 days, etc. I have got a help that thing. But it is in Magento 1.9, not 2.x from here https://stackoverflow.com/questions/48299911/get-last-7-days-best-selling-items-magento-1-9 and I've tried a lot in Magento 2.3, but shows a blank page that's main code are given below:

    $bestSellers = $this->_bestSellersCollectionFactory->create();
                         //->setModel('Magento\Catalog\Model\Product');

    $bestSellers->addAttributeToSelect('*')->addFieldToFilter('created_at', array(
                'from'=> date('Y-m-d H:i:s', strtotime('-7 days')),
                'to' => date('Y-m-d H:i:s')
                                ));

   foreach ($bestSellers as $product) {
            $productIds[] = $product->getProductId();
        }

   $collection = $this->productCollectionFactory->create()->addIdFilter($productIds);
   $collection->addMinimalPrice()
            ->addFinalPrice()
            ->addTaxPercents()
            ->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
            ->addStoreFilter($this->getStoreId())
            ->addUrlRewrite()
            ->setVisibility($this->catalogProductVisibility->getVisibleInSiteIds());
            //->setPageSize($this->getProductsCount());

    return $collection;

I cann't understand where I'm wrong and how to implement this thing. If any one knows, please help me. Thank You.

1 Answer 1

0

I did the collection like this:

// some more lines in advance - let me know if I should append them
    public function getBestSellerCollection($from, $to) 
{
    $bestSellerProdcutCollection = $this->_collectionFactory->create();
    $bestSellerProdcutCollection->setModel('Magento\Catalog\Model\Product')->setPeriod('day');    
    $datefrom = date('Y-m-d', strtotime('-'.$from.' day'));
    $dateto = date('Y-m-d', strtotime('-'.$to.' day'));
    $bestSellerProdcutCollection->addFieldToFilter('period',array('gt'=>$datefrom));
    $bestSellerProdcutCollection->getSelect()->group('Product_Name')->order('Product_Name ASC'); //DESC ASC
    return $bestSellerProdcutCollection;
}

Then later you can call

$collection =  $block->getBestSellerCollection(30,0); // last 30 days

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.