How to display best selling products on homepage in magento 2

Posted On: October 29, 2017
best seller widget magento2

If you want to get best selling product at the home page then you can just call widget in magento 2. In this article we will teach you how to create magento 2 widget for best selling products.

First create the registration.php file at below mentioned path:

File Path: app\code\Sellpr\Bestsellerw\registration.php and add below code:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Sellpr_Bestsellerw',
    __DIR__
);

Now create composer.json file in the same path with below code:

{
    "name": "Sellpr/Bestsellerw",
    "description": "Sellpr Bestseller product widget",
    "require": {
        "php": "~5.5.0|~5.6.0|~7.0.0"
    },
    "type": "magento2-module",
    "version": "1.0.0",
    "license": [
        "Commercial"
    ],
    "autoload": {
        "files": [ "registration.php" ],
        "psr-4": {
            "Sellpr\\Bestsellerw\\": ""
        }
    }
}

Than create Bestsellerdproduct.php file in below mentioned path with the following code:

File Path: app\code\Sellpr\Bestsellerw\Block\Widget\Bestsellerdproduct.php

<?php
namespace Sellpr\Bestsellerw\Block\Widget;

class Bestsellerdproduct extends \Magento\Framework\View\Element\Template implements \Magento\Widget\Block\BlockInterface
{
	protected $_template = 'widget/bestsellerdproduct.phtml';
	 
    const DEFAULT_PRODUCTS_COUNT = 10;
     const DEFAULT_IMAGE_WIDTH = 150;
     const DEFAULT_IMAGE_HEIGHT = 150;
     protected $_productsCount;
    protected $httpContext;
    protected $_resourceFactory;
    protected $_catalogProductVisibility;
    protected $_productCollectionFactory;
    protected $_imageHelper;
    protected $_cartHelper;
   public function __construct(
    \Magento\Catalog\Block\Product\Context $context,
        \Magento\Reports\Model\ResourceModel\Report\Collection\Factory $resourceFactory,
        \Magento\Reports\Model\Grouped\CollectionFactory $collectionFactory,
        \Magento\Reports\Helper\Data $reportsData,
        array $data = []
    ) {
        $this->_resourceFactory = $resourceFactory;
        $this->_collectionFactory = $collectionFactory;
        $this->_reportsData = $reportsData;
              $this->_imageHelper = $context->getImageHelper();
        $this->_cartHelper = $context->getCartHelper();
        parent::__construct($context, $data);
    }
 
 public function imageHelperObj(){
        return $this->_imageHelper;
    }
    /**
     get featured product collection
     */
   public function getBestsellerProduct(){
     $limit = $this->getProductLimit();
       

		$resourceCollection = $this->_resourceFactory->create('Magento\Sales\Model\ResourceModel\Report\Bestsellers\Collection');
		$resourceCollection->setPageSize($limit);
		return $resourceCollection;
   }
   
    /**
      Get the configured limit of products
     */
    public function getProductLimit() {
		if($this->getData('productcount')==''){
			return DEFAULT_PRODUCTS_COUNT;
		}
        return $this->getData('productcount');
    }
  public function getProductimagewidth() {
		if($this->getData('imagewidth')==''){
			return DEFAULT_IMAGE_WIDTH;
		}
        return $this->getData('imagewidth');
    }
     
    public function getProductimageheight() {
		if($this->getData('imageheight')==''){
			return DEFAULT_IMAGE_HEIGHT;
		}
        return $this->getData('imageheight');
    }
     public function getAddToCartUrl($product, $additional = [])
    {
			return $this->_cartHelper->getAddUrl($product, $additional);
    }
     
    public function getProductPriceHtml(
        \Magento\Catalog\Model\Product $product,
        $priceType = null,
        $renderZone = \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST,
        array $arguments = []
    ) {
        if (!isset($arguments['zone'])) {
            $arguments['zone'] = $renderZone;
        }
        $arguments['zone'] = isset($arguments['zone'])
            ? $arguments['zone']
            : $renderZone;
        $arguments['price_id'] = isset($arguments['price_id'])
            ? $arguments['price_id']
            : 'old-price-' . $product->getId() . '-' . $priceType;
        $arguments['include_container'] = isset($arguments['include_container'])
            ? $arguments['include_container']
            : true;
        $arguments['display_minimal_price'] = isset($arguments['display_minimal_price'])
            ? $arguments['display_minimal_price']
            : true;

        $priceRender = $this->getLayout()->getBlock('product.price.render.default');

        $price = '';
        if ($priceRender) {
            $price = $priceRender->render(
                \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
                $product,
                $arguments
            );
        }
        return $price;
    }
}

Next create module.xml file in below mentioned file:

Also Read :   Magento 2 Theme Development Tutorial

File Path: app\code\Sellpr\Bestsellerw\etc\module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Sellpr_Bestsellerw" setup_version="1.0.0">
    </module>
</config>
Next, in the same path create widget.xml file with the following code:
<?xml version="1.0" encoding="UTF-8"?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Magento/Widget/etc/widget.xsd">
	<widget id="Sellpr_Bestsellerw" class="Sellpr\Bestsellerw\Block\Widget\Bestsellerdproduct">
		<label translate="true">Bestseller Product Widget</label>
		<description>Sellpr Bestseller Product Widget</description>
		<parameters>
			<parameter name="productcount" xsi:type="text"  visible="true" sort_order="1" >
				<label translate="true">Product Count</label>
			</parameter>
			<parameter name="imagewidth" xsi:type="text"  visible="true" sort_order="2" >
				<label translate="true">Image Width</label>
			</parameter>
			<parameter name="imageheight" xsi:type="text"  visible="true" sort_order="3" >
				<label translate="true">Image Height</label>
			</parameter>
		</parameters>
	</widget>
</widgets>

Now create bestsellerdproduct.phtml file in the below mentioned path with the following code:

File Path: app\code\Sellpr\Bestsellerw\view\frontend\templates\widget\ bestsellerdproduct.phtml

<?php
if ($exist = ($this->getBestsellerProduct() && $this->getBestsellerProduct()->getPageSize())) {
$wet_prodcollection = $this->getBestsellerProduct();
$productcount = $this->getProductLimit();
$imagewidth = $this->getProductimagewidth();
$imageheight = $this->getProductimageheight();
 $mode = 'grid';
  $title = __('Bestseller Products');
 $type = 'widget-bestseller-grid';
 $image = 'bestseller_products_content_widget_grid';
}
?>



<?php if ($exist):?>
  <div class="block widget block-bestseller-products <?php echo $mode; ?>">
        <div class="block-title">
            <strong role="heading" aria-level="2"><?php  echo $title; ?></strong>
        </div>
<div class="block-content">
 <?php  echo '<!-- ' . $image . '-->' ?>
 <div class="products-<?php echo $mode; ?> <?php echo $mode; ?>">
                <ol class="product-items <?php echo $type; ?>">
                    <?php $iterator = 1; ?>
    <?php foreach ($wet_prodcollection as $item):     
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$_product = $objectManager->get('Magento\Catalog\Model\Product')->load($item->getProductId());
    ?>
    
     <?php echo($iterator++ == 1) ? '<li class="product-item">' : '</li><li class="product-item">' ?>
                        <div class="product-item-info">
    <?php 
            $image_url = $block->imageHelperObj()->init($_product, 'product_page_image_small')
                        ->setImageFile($_product->getFile())
                        ->resize($imagewidth,$imageheight)
                        ->getUrl();
?>
                            <a href="<?php  echo $_product->getProductUrl() ?>" class="product-item-photo">
                               <img src="<?php echo  $image_url;?>" alt="<?php echo $this->escapeHtml($_product->getName()) ?>" />
                            </a>
                            <div class="product-item-details">
                                <strong class="product-item-name">
                                    <a title="<?php echo $block->escapeHtml($_product->getName()) ?>"
                                       href="<?php echo $_product->getProductUrl() ?>"
                                       class="product-item-link">
                                        <?php echo $block->escapeHtml($_product->getName()) ?>
                                    </a>
                                </strong>
                                <?php
                                echo $this->getProductPriceHtml($_product, $type);
                                ?> 
                                    <div class="product-item-actions"> 
                                            <div class="actions-primary">
                                                <?php if ($_product->isSaleable()): ?>
                                                    <?php if ($_product->getTypeInstance()->hasRequiredOptions($_product)): ?>
                                                        <button class="action tocart primary"
                                                                data-mage-init='{"redirectUrl":{"url":"<?php  echo $block->getAddToCartUrl($_product) ?>"}}'
                                                                type="button" title="<?php echo __('Add to Cart') ?>">
                                                            <span><?php echo __('Add to Cart') ?></span>
                                                        </button>
                                                    <?php else: ?>
                                                        <?php
                             $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
                               $postData = $postDataHelper->getPostData($block->getAddToCartUrl($_product), ['product' => $_product->getId()]);
                                                        ?>
                                                        <button class="action tocart primary"
                                                                data-post='<?php echo $postData; ?>'
                                                                type="button" title="<?php echo __('Add to Cart') ?>">
                                                            <span><?php echo __('Add to Cart') ?></span>
                                                        </button>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <?php if ($_product->getIsSalable()): ?>
                                                        <div class="stock available"><span><?php echo __('In stock') ?></span></div>
                                                    <?php else: ?>
                                                        <div class="stock unavailable"><span><?php echo __('Out of stock') ?></span></div>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </div> 
                                    </div> 
                            </div>    
       </div>
     		<?php echo($iterator == count($wet_prodcollection)+1) ? '</li>' : '' ?>
                    <?php endforeach ?>
</ol>
</div>
<?php endif;?>

Now run the below commands:

Also Read :   WooCommerce customer completed order notification emails

php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy

chmod -R 777 var pub static

Now you can add widget at your desired place.

If you still have any question or want to ask a question, you can contact us or ask your question with us. For more tutorials you can visit our other articles or visit questions page.

You can join us on twitter or subscribe us on YouTube for more web design & development tutorials.

Related Post

X
Subscribe to our newsletter
Subscribe to our newsletter today to receive updates on the latest news and offers.
100% Privacy. No spam guaranteed
webe tutorial
Menu