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

magento 1 extension converted in to magento 2 process

Simple Install =================================== Download as a zip below link. unzip and upload it to your public_html or other rootdoc directory. https://github.com/magento/code-migration. login to your server via shell switch to the code-migration-develop directory by running following command   cd code-migration-develop Run command following command in root directory of this toolkit composer instal Before running the migration, the following directories need to be prepared: ===================================== * `<src>` - Directory that contains custom Magento 1.x code that is intended to be migrated. The code must follow the Magento 1.x directory structure.   Magento1.x core files must not be included. * `<dst>` - Empty directory for the toolkit to put the generated Magento 2 code to * `<m1>` - Directory that contains: * Vanilla Magento 1.x codebase, and * Custom Magento 1.x code same as...

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...

Magento Debug HEADERS ALREADY SENT error

When you  receiving the following error in  system.log file: app\code\core\Mage\Core\Controller\Response\Http.php:44  [1] \www.pawan.com\lib\Zend\Controller\Response\Abstract.php:727  [2]  \www.pawan.com\app\code\core\Mage\Core\Controller\Response\Http.php:75  [3]  \www.pawan.com\app\code\core\Mage\Core\Controller\Varien\Front.php:188  [4]  \www.pawan.com\app\code\core\Mage\Core\Model\App.php:304  [5]  \www.pawan.com\app\Mage.php:596  [6]  \www.pawan.com\index.php:81 if you have no idea what file is causing this. Here is the steps to debug. That error is thrown from Mage_Core_Controller_Response_Http -> sendHeaders(). This function calls the super class function that actually does the check to see whether or not headers have already been sent, Zend_Controller_Response_Abstract -> canSendHeaders(). The Zend_Controller_Response_Abstract class handles, among other things, sending response header...