Skip to main content

magento 2 best seller product display based on current category and subcategories

Magento 2 getting best seller based on category wise displaying i have done below for that to implement this functionality it is working fine for me.

step 1 create block file in our module folder

<?php
namespace Pawan\Bestseller\Block;
use Magento\Catalog\Api\CategoryRepositoryInterface;
class Bestsellercategory extends \Magento\Catalog\Block\Product\ListProduct {

    /**
     * Product collection model
     *
     * @var Magento\Catalog\Model\Resource\Product\Collection
     */
    protected $_collection;

    /**
     * Product collection model
     *
     * @var Magento\Catalog\Model\Resource\Product\Collection
     */
    protected $_productCollection;

    /**
     * Image helper
     *
     * @var Magento\Catalog\Helper\Image
     */
    protected $_imageHelper;

    /**
     * Catalog Layer
     *
     * @var \Magento\Catalog\Model\Layer\Resolver
     */
    protected $_catalogLayer;

    /**
     * @var \Magento\Framework\Data\Helper\PostHelper
     */
    protected $_postDataHelper;

    /**
     * @var \Magento\Framework\Url\Helper\Data
     */
    protected $urlHelper;

    /**
     * @var \Magento\Catalog\Helper\Image
     */
    protected $imageHelper;

    /**
     * @var \Magento\Catalog\Helper\Image
     */
    protected $_scopeConfig;

    /**
     * @var \Magento\Catalog\Api\CategoryRepositoryInterface
     */
    protected $categoryRepository;

    protected $_registry;
    /**
     * Initialize
     *
     * @param \Magento\Catalog\Block\Product\Context $context
     * @param \Magento\Framework\Data\Helper\PostHelper $postDataHelper
     * @param \Magento\Catalog\Model\Layer\Resolver $layerResolver
     * @param \CategoryRepositoryInterface $categoryRepository
     * @param \Magento\Framework\Url\Helper\Data $urlHelper
     * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Catalog\Helper\Image $imageHelper
     * @param array $data
     */
    public function __construct(
    \Magento\Catalog\Block\Product\Context $context, \Magento\Framework\Data\Helper\PostHelper $postDataHelper, \Magento\Catalog\Model\Layer\Resolver $layerResolver, CategoryRepositoryInterface $categoryRepository, \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollection, \Magento\Framework\Url\Helper\Data $urlHelper, \Magento\Catalog\Model\ResourceModel\Product\Collection $collection, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Catalog\Helper\Image $imageHelper,\Magento\Framework\Registry $registry, array $data = []
    ) {
        $this->imageBuilder = $context->getImageBuilder();
        $this->_catalogLayer = $layerResolver->get();
        $this->_postDataHelper = $postDataHelper;
        $this->categoryRepository = $categoryRepository;
        $this->urlHelper = $urlHelper;
        $this->_collection = $collection;
        $this->_imageHelper = $imageHelper;
        $this->_scopeConfig = $scopeConfig;
        $this->_registry = $registry;
        parent::__construct($context, $postDataHelper, $layerResolver, $categoryRepository, $urlHelper, $data);
    }

    /**
     * Get product collection
     */
    protected function getProducts() {
        $limit = $this->getProductLimit();
        $sortby = 'rand()';
        $storeId = 0;
        $time = $this->getTimePeriod();

        $today = strtotime($this->_localeDate->date()->format('Y-m-d H:i:s'));
        $last = $today - (60 * 60 * 24 * $time);
        $from = date("Y-m-d H:i:s", $last);
        $to = date("Y-m-d H:i:s", $today);


        $fromDate = date("Y-m-d H:i:s", $last); //$this->getStartDate();
        $toDate = date("Y-m-d H:i:s", $today); //$this->getEndDate();
        
        $category = $this->_registry->registry('current_category');//get current category
//        $category->getId();
//        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/bestseller.log');
//        $logger = new \Zend\Log\Logger();
//        $logger->addWriter($writer);
       
        $categoryObj = $this->categoryRepository->get($category->getId());
        $subcategories = $categoryObj->getChildrenCategories();
        foreach($subcategories as $subcategorie) {
            $subcatids[] = $subcategorie->getId();
            $subcatnames[] = $subcategorie->getName();
            if($subcategorie->hasChildren()) {
                $childCategoryObj = $this->categoryRepository->get($subcategorie->getId());
                $childSubcategories = $childCategoryObj->getChildrenCategories();
                foreach($childSubcategories as $childSubcategorie) {
                   $subcatids[] = $childSubcategorie->getId();
                   $subcatnames[] = $childSubcategorie->getName();
                }
            }
        }
//        $logger->info($this->getProductLimit());
       
        
        $sqlQuery = "e.entity_id = aggregation.product_id";
        if ($storeId > 0) {
            $sqlQuery .=" AND aggregation.store_id={$storeId}";
        }
        if ($fromDate != '' && $toDate != '') {
            $sqlQuery .=" AND aggregation.period BETWEEN '{$fromDate}' AND '{$toDate}'";
        }
        $this->_collection->clear()->getSelect()->reset('where');
        $collection = $this->_collection
                ->addMinimalPrice()
                ->addFinalPrice()
                ->addTaxPercents()
                ->addAttributeToSelect('name')
                ->addAttributeToSelect('image')
                ->addAttributeToSelect('news_from_date')
                ->addAttributeToSelect('news_to_date')
                ->addAttributeToSelect('special_price')
                ->addAttributeToSelect('special_from_date')
                ->addAttributeToSelect('special_to_date')
                ->addAttributeToSelect('*');
//          ->addAttributeToFilter('is_saleable', 1, 'left')
//          ->addAttributeToFilter('status', 1)
//          ->addAttributeToFilter('visibility', 4);
        $collection->addCategoriesFilter(["in" => $subcatids]);
        if ($this->getSortbyCollection() == "product_name") {
            $sortby = "rand()";
        } else if ($this->getSortbyCollection() == "product_price") {
            $sortby = "price DESC";
        } else if ($this->getSortbyCollection() == "qty_ordered") {
            $sortby = "sold_quantity DESC";
        }
        $collection->getSelect()->joinRight(
                array('aggregation' => 'sales_bestsellers_aggregated_monthly'), $sqlQuery, array('SUM(aggregation.qty_ordered) AS sold_quantity')
        )->group('e.entity_id')->order($sortby)->limit($limit);
        $collection->getSelect();

        $this->_productCollection = $collection;
        return $this->_productCollection;
    }

    /*
     * Load and return product collection 
     */

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

    /*
     * Get product toolbar
     */

    public function getToolbarHtml() {
        return $this->getChildHtml('pager');
    }

    /*
     * Get grid mode
     */

    public function getMode() {
        return 'grid';
    }

    /**
     * Get image helper
     */
    public function getImageHelper() {
        return $this->_imageHelper;
    }
    public function getTimePeriod() {
        return $this->_scopeConfig->getValue('bestseller/setting/time', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
    }

    public function getProductLimit() {
        //return $this->_scopeConfig->getValue('bestsellerproducts_settings/vertical_setting/limit', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        return $this->_scopeConfig->getValue('bestseller/setting/row', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
    }

    public function getVisibleStatus() {

        $visibleStatus = 4;
        return $visibleStatus;
    }

}
?>
step2 :: get products in your phtml file  by calling below format


<?php $_products = $block->getLoadedProductCollection(); ?>
<?php
echo "<pre />";
foreach ($_productCollection as $_product):
//    print_r($_product->getData());
   echo $_product->getName()."<br />";
endforeach;
?>



Comments

  1. Magento is highly trustable e-commerce platform by worlds leading brands and also it is used by most of the small businesses and startup level companies. After few years of development Magento 2 were released for their customers. We upgrade your existing magento 1.x shop to magento 2 or built a new Magento 2 website from scratch with enhanced Scalability, Performance and security.

    Magento Migration Link: https://bit.ly/2O4hzBu

    ReplyDelete
  2. Hi,
    I want to create a best seller products widget.How can I create widget using above code?
    Please guide me about which files I need to create.
    Thanks

    ReplyDelete
    Replies
    1. Hi Shoaib,
      Sorry for late reply i have n't seen your message i think you got solution if not let me know i will tell

      Delete
  3. Are you thinking to use Advantages of Oracle Database for your work or business? A reliable storage will store the data from a database, that's the main purpose of using DBMS. Using ACID test, Oracle ensures the top level reliability of your system. As well as, delivers high integrity of data storage.

    ReplyDelete
  4. Keep up the good work PawanMagento blogspot. Keep sharing!

    Laravel framework helps in designing of online store. This framework has an inbuilt feature that makes the user experience wonderful. Unisoft Informatics is the Top and Affordable Laravel Development Company that creates a website with full-fledged benefits. We give our best to deliver the project according to clients' requirements.

    ReplyDelete

Post a Comment

Popular posts from this blog

Integrity constraint violation: 1052 Column 'created_at' in where clause is ambiguous

When trying to filter sales order grid with From and To dates it was redirecting to dashboard.after that again i tried to open sales order grind it is generating reports in reports file it showing. "Integrity constraint violation: 1052 Column 'created_at' in where clause is ambiguous" means it is finding a another created_at field. because when we adding or joining the other table then it has also a field named as created_at. So below is the  solution for this error. magento that created_at is of the main_table not of my custom table. Find the below code in the sales order grid.php file. $this->addColumn('created_at', array(            'header' => Mage::helper('sales')->__('Purchased On'),             'index' => 'created_at',             'type' => 'datetime',             'width' => '100px',         )); ...

Magento 2 product collection Filtering multi-select attribute values

  If you have multi-select attribute of product like below If you want filter value for this option Use below syntax to get product data: ->addAttributeToFilter('store_model', array('finset' => $params['store_model'])) finset key is used for multiselect attribute filter. $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $products = $objectManager->get('Magento\Catalog\Model\Product')         ->getCollection()         ->addAttributeToSelect('*')         ->addAttributeToSelect('store_brand')         ->addAttributeToSelect('store_model')         ->addAttributeToSelect('store_year')         ->addAttributeToFilter('store_brand', array('finset' => $params['store_brand']))         ->addAttributeToFilter('store_model', array('finset' => $params['store_model']))         ->ad...

How to Add Magento 2 Sort by Price for Low to High & High to Low Options and name A-Z & Z-A etc sort dropdown

The store design and its navigation must be in such a way that makes it easier for the shopper to find the exact required product and make the shopping process comfortable and enjoyable.  Navigation can be made easier and hence improve the shopping experience by offering custom sorting options. The default Magento 2 offers sorting by position, product name, and price  A price-sensitive customer may save some clicks by starting with the cheapest products. On the other hand, customers who have a high standard for quality may quickly find their most desired products by sampling from high prices to low prices. To provide such feature in Magento 2 and serve both the type of price-sensitive customers, you can add Magento 2 sort by price for low to high & high to low options. Some people can sort by names A-Z or Z-A, position low to high high to low like this we can improve sales to our site and user can easily find products for implementing this fallow given steps to implement s...