0

I wish to show best selling products in homepage.Please provide me a solution to get best selling products and display in home page.
Thanks

0

Step 1: Create a block file

namespace {custom namespace}\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;
   }
}

Step 2: 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> 
.
.
.
.
.
.

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.