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

1

1 Answer 1

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> 
.
.
.
.
.
.
1
  • how can we get today, last month, last 3 month best seller product using this code? – Commented Oct 13, 2022 at 10:10

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.