4

I want to display bestselling products for time inetrval 7 days. We can set period by day, month and year

$bestSellers = $this->_bestSellersCollectionFactory->create()
            ->setPeriod('day');

Can we set the date range to show only products from last 7 days like we set in admin enter image description here

0

Step1 : Create the Block

<?php
namespace Asad\HelloWorld\Block;
class BestSeller extends \Magento\Framework\View\Element\Template
{

    protected $_collectionFactory;
   public function __construct(
       \Magento\Backend\Block\Template\Context $context,
      \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
               array $data = []
   ) {

       $this->_collectionFactory = $collectionFactory;
             parent::__construct($context, $data);
   }


public function getBestSellerData(){

$bestSellerProdcutCollection = $this->_collectionFactory->create()
                    ->setModel('Magento\Catalog\Model\Product')
                    ->setPeriod('month') //you can add period daily,yearly
                   ;

       return $bestSellerProdcutCollection;
   }
}

Step2 : Show Output
Getting collection in phtml file from block.

<?php
        $bestSeller =  $block->getBestSellerData(); ?>
        <h1>Best Seller Collection.....</h1>
        <ul>
            <?php foreach ($bestSeller as $product) {
                ?>
                <li><?php  echo $product->getProductName();?>--<?php  echo $product->getQtyOrdered();?></li>
            <?php } ?>
</ul>

I hope this will work for you

  • I already created the block but it shows all products but I want best selling products from period of 7 days. – Ankita Agrawal Jun 27 at 13:03
  • did you try ->setPeriod('week') – Asad Khan Jun 27 at 13:49
  • Yes but it is not working, is there any option to set time interval as we set in admin – Ankita Agrawal Jun 28 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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