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 :   How to Create a Custom Page in WordPress

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 :   Things That Assist Boost Breast Milk

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 *

13 − 7 =

Blog

Ways to Increase Comments on Your Blog

mm

Published

on

Ways to Increase Comments on Your Blog

Everyone knows commenting on the other website blogs give the benefits of backlinks, traffic, and branding of our linked website and we are trying lots of things to create a good backlinks which would give a huge converting traffic to us. Sometime people commenting a those website which doesn’t have good reputation or not a much traffic so, their efforts are not useful for them.

Commenting is the ways to drive traffic that is facebook commenting, twitter commenting or website commenting. Here we are going to tell you about some points which may give you huge traffic to increase comments on your blog.

Blog Comment Points Are:

Get visitors to subscribe: Many readers don’t want to comment at first time on your blog because they don’t have much truest on your blog and they don’t know about how much the traffic on your blog getting. To ask them to subscribe to your blog for more blog or webinar this will help to increase comments, traffic and revenue.

Also Read :   How to Display Products on the homepage in Magento 2?

Disable spam prevention methods: If you are using captcha, then you need to remove them so user can comment without any interruption.

Avoid forcing registration: If you are using registration process for commenting on your site ten remove them because this create far too much resistance and makes it much more irritate for your visitors to comment.

Link to your comments section at the end of your post: Lot of blog themes have a problem with its comment section, visitors have to scroll the whole page at the bottom for the commenting. Your blog should have comment link at the top of page with blog title where visitor can click and move directly to comment section.

Go back and think about the audience you’re trying to reach: If you are getting many comments then try to give answer of your visitors which give your attention to your visitor and help you to reach your goal and focus on the right areas.

Also Read :   Magento 2 theme development tutorial

Leave an unanswered question at the end of your post: Ask a question at the end of blog which is the one of the best ways to get readers attention to comment on your blog. Your aim should to develop a discussion within your comments and the more discussion.

Respond to comments and encourage more conversations: As we talk in Go back and think about the audience you’re trying to reach engaging your audience for getting more comments in general ways to respond to comments for further conversation.

You can let us your point of views in the comment or subscribe us to get more blog from us.

Continue Reading

Trending