To get best seller collection, try to do as follows:
Step 1: Firstly, Create one block file on our custom extension
add Blockname.php in the following path
<?php
namespace Vendor\Extension\Block;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory as BestSellersCollectionFactory;
use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;
class Blockname extends Template
{
protected $_bestSellersCollectionFactory;
protected $_productCollectionFactory;
protected $_storeManager;
public function __construct(
Context $context,
CollectionFactory $productCollectionFactory,
StoreManagerInterface $storeManager,
BestSellersCollectionFactory $bestSellersCollectionFactory,
) {
$this->_bestSellersCollectionFactory = $bestSellersCollectionFactory;
$this->_storeManager = $storeManager;
$this->_productCollectionFactory $productCollectionFactory;
parent::__construct($context);
}
public function getProductCollection()
{
$productIds = [];
$bestSellers = $this->_bestSellersCollectionFactory->create()
->setPeriod('month');
foreach ($bestSellers as $product) {
$productIds[] = $product->getProductId();
}
$collection = $this->_productCollectionFactory->create()->addIdFilter($productIds);
$collection->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->addAttributeToSelect('*')
->addStoreFilter($this->getStoreId())
->setPageSize(count($productIds));
return $collection;
}
public function getStoreId(){
return $this->_storeManager->getStore()->getId();
}
}
Step 2: After the above step Insert the below code in phtml file at the following path.
app\code\Vendor\Extension\view\frontend\templates\list.phtml.
<?php
$collection = $block->getProductCollection();
foreach ($collection as $_product)
{
echo $product->getName() . ' - ' . $product->getProductUrl() . '<br />';
}
Step 3: Flush Cache and view the result.