Connect with us

Blog

How to display best selling products on homepage in magento 2

mm

Published

on

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 :   Wall Street vs. Main Street : Investing and economics

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 :   Cost of Living in Abu Dhabi - Prices in Abu Dhabi

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.

Hi, Thank you for reading my article. I am Victor, a professional blogger from Jaipur, India.I started webetutorial for blogging & sharing solution for developer questions, and now it’s empowering globally by helping them to make money.I am writing about starting & managing a blogs, WordPress, Magento, Social Media, SEO, Marketing, making money online, Investment, Finance, Gadgets, Fitness and more.

Continue Reading
Advertisement
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

16 − five =

Blog

Keys to Blogging Success: How to Write an Awesome Blog Post

mm

Published

on

Keys to Blogging Success: How to Write an Awesome Blog Post

In this article we will talk about how to write a quality blog post. This article will give you some idea to enhance your post quality and increase content word limit.

Follow the below points to write a blog:

Make A Plan:

Before starting on any blog we have to make a plan on which topic we are going to write and how many words we can write. We need to choose the words and headings of content on which readers is driving on search engine. Blog plan will maintain a well-created synopsis with a target goal to reach your readers.

Create A Good Title Of Blog:

You need to stand out in the today competition need a good title for your blog which define your whole blog in a single line. Your title should be completed in a 60 characters because greater title will escape by some search engine like Google.

Make sure your blogs all point is clear from the beginning which creates a connection between you and your readers not only for current blog they will connect for further blogs.

Also Read :   Product Attachment for Magento 2

Keep It Clean & Formatted:

Blog content should be proper aligned and well-formatted with an organized structure. Only need to describe the information which is important and will not confuse your reader.

First all blogs should write in the Microsoft word or open word which gives formatted structure to your blog and make low chance for wrong spell.  After ensuring that your post is good enough and everything looks fine to be published upload content on your live blogging website.

Write Down The Truth:

When you are going to write a any blog you need to write down the truth content because readers only love true websites. You also need to respect your readers and competitor bloggers to increase traffic on your website.

On-Page SEO:

Blog must have SEO friendly title, meta keywords, meta description, Image alt tags, Headings, Inbound and outbound links. On-page seo will give change to your blog to show on top of search result in search engines. For the WordPress blogs you can install and configuring Yoast SEO plugin.

Also Read :   Web Hosting: Shared, Cloud, VPS Hosting & Dedicated from hostgator

Wrap Up:

Once you have completed your blog you should write a 2-3 line of short description which you have wrote because that will wrapping your blog overview and make your blog attractive.

For example: In this blog we talk about grows in traffic, revenue, authority topic and sharing personal experiences. The all of things describe here will increase your content quality for blogs.

To get more news on content writing, subscribe us or join us to advertise your blog with us.

Continue Reading

Subscribe to our newsletter

Enter your email address to subscribe to blog and receive notifications of new articles by email.
100% Privacy. No spam guaranteed

Trending