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
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;
?>
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.
ReplyDeleteMagento Migration Link: https://bit.ly/2O4hzBu
Hi,
ReplyDeleteI 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
Hi Shoaib,
DeleteSorry for late reply i have n't seen your message i think you got solution if not let me know i will tell
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.
ReplyDeleteAmazing posst! thanks for sharing...
ReplyDeleteWhat is Sensex
Sensitive Index
S&P BSE Sensex
BSE Sensex Index
Keep up the good work PawanMagento blogspot. Keep sharing!
ReplyDeleteLaravel 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.