0

I am new in magento . I want create new block for "Best selling product" in home page. How can I get "Monthly Best selling product" in Magento 2? Any free extension for this or How to do programatically? Anyone help?

0

You can create a Block in your cutom Module to get the bestseller product by date range.

I assume your custom module name is Company_MyModule.

Steps are given below to get bestseller pro

step 1)

Create a Block Bestsellers.php under YOUR-MAGENTOROOT/app/code/Company/MyModule/Block

<?php

namespace Company\MYModule\Block;

class Bestsellers extends \Magento\Catalog\Block\Product\AbstractProduct {

    protected $_catalogProductVisibility;

    protected $_productCollectionFactory;

    protected $_categoryFactory;

    protected $urlHelper;

    protected $_resource;

    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        \Magento\Framework\App\ResourceConnection $resource,
        array $data = []
    ) {
        $this->_categoryFactory = $categoryFactory;
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->_catalogProductVisibility = $catalogProductVisibility;
        $this->urlHelper = $urlHelper;
        $this->_resource = $resource;

        parent::__construct($context, $data);
    }

    public function getProducts() {
        $count = $this->getProductCount();
        $category_id = $this->getData("category_id");
        $collection = $this->_productCollectionFactory->create();
        $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());
        $collection = $this->_addProductAttributesAndPrices($collection)->addStoreFilter();
        if(!$category_id) {
            $category_id = $this->_storeManager->getStore()->getRootCategoryId();
        }
        $category = $this->_categoryFactory->create()->load($category_id);
        $connection  = $this->_resource->getConnection();
        if(isset($category) && $category) {
            $collection->addMinimalPrice()
                ->addFinalPrice()
                ->addTaxPercents()
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('image')
                ->addAttributeToSelect('small_image')
                ->addAttributeToSelect('thumbnail')
                ->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
                ->addUrlRewrite()                
                ->addCategoryFilter($category);
        } else {
            $collection->addMinimalPrice()
                ->addFinalPrice()
                ->addTaxPercents()
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('image')
                ->addAttributeToSelect('small_image')
                ->addAttributeToSelect('thumbnail')
                ->addAttributeToSelect($this->_catalogConfig->getProductAttributes())
                ->addUrlRewrite();

        }

        $fromtDate = new DateTime('2019-10-01');// START Date
        $toDate = new DateTime('2019-10-30'); // END Date
        $fromtDate =  $fromtDate->format('Y-m-d H:i:s 0:0:0');
        $toDate =  $toDate->format('Y-m-d H:i:s 11:59:59');



         $collection
          ->addAttributeToFilter('created_at', array('gteq'=> $fromtDate))
          ->addAttributeToFilter('created_at', array('lteq'=> $toDate))
          ->joinLeft(['soi' => $connection->getTableName('sales_order_item')], 'soi.product_id = e.entity_id', ['SUM(soi.qty_ordered) AS ordered_qty'])
          ->join(['order' => $connection->getTableName('sales_order')], "order.entity_id = soi.order_id",['order.state'])
          ->where("order.state <> 'canceled' and soi.parent_item_id IS NULL AND soi.product_id IS NOT NULL ")
          ->group('soi.product_id')
         ->limit($count); 
        return $collection;
    }

    public function getAddToCartPostParams(\Magento\Catalog\Model\Product $product)
    {
        $url = $this->getAddToCartUrl($product);
        return [
            'action' => $url,
            'data' => [
                'product' => $product->getEntityId(),
                \Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED =>
                    $this->urlHelper->getEncodedUrl($url),
            ]
        ];
    }

    public function getLoadedProductCollection() {
        return $this->getProducts();
    }

    public function getProductCount() {
        $limit = $this->getData("product_count");
        if(!$limit)
            $limit = 10;
        return $limit;
    }
}

step 2)

In Phtml get Bestseller Product Collection like this.

<?php
$_productCollection = $block->getLoadedProductCollection();
 foreach ($_productCollection as $_product):
    echo $_product->getName()."<br />";
 endforeach;
?>
| improve this answer | |
  • I am not getting you.. Can you explain in details? – Praful Nov 29 '19 at 4:22

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.