Magento – magento 2 best seller ,most viewed and Wishlist product collection

magento2productproduct-collection

Hi can you please anyone give me the working code of best seller ,most viewed collection and Wishlist Product collection

I try with multiple codes but unfortunately, i am not getting any result

Index.php

<?php

namespace MPS\Test\Block\Bestproduct;


class Index extends \Magento\Framework\View\Element\Template implements \Magento\Widget\Block\BlockInterface
{
    /**
     * Default value for products count that will be shown
     */
    const DEFAULT_PRODUCTS_COUNT = 100;
    /**
     * Products count
     *
     * @var int
     */
    protected $_productsCount;
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    protected $httpContext;
    protected $_resourceFactory;
    /**
     * Catalog product visibility
     *
     * @var \Magento\Catalog\Model\Product\Visibility
     */
    protected $_catalogProductVisibility;

    /**
     * Product collection factory
     *
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $_productCollectionFactory;

    /**
     * Image helper
     *
     * @var Magento\Catalog\Helper\Image
     */
    protected $_imageHelper;
     /**
     * @var \Magento\Checkout\Helper\Cart
     */
    protected $_cartHelper;
    /**
     * @param Context $context
     * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
     * @param \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility
     * @param \Magento\Framework\App\Http\Context $httpContext
     * @param array $data
     */
   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);
    }

    /**
     * get featured product collection
     */
   public function getBestsellerProduct(){
     $limit = self::DEFAULT_PRODUCTS_COUNT;

        $resourceCollection = $this->_resourceFactory->create('Magento\Sales\Model\ResourceModel\Report\Bestsellers\Collection');
        $resourceCollection->setPageSize($limit);
        return $resourceCollection;
   }



}

bestProducts.phtml

<?php $bestSellingCollection =  $block->getBestsellerProduct();
echo $bestSellingCollection->count();
print_r($bestSellingCollection->getData());
?>

I got some random product. I deleted all order and products in backend that deleted products showing in Bestseller collection

Most Viewed product

Index.php

<?php

namespace MPS\Test\Block\Mostproduct;


class Index extends \Magento\Framework\View\Element\Template implements \Magento\Widget\Block\BlockInterface
{
     /**
     * @var \Magento\Reports\Model\ResourceModel\Product\CollectionFactory
     */
    protected $_productsFactory;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory,
        array $data = []
    ) {
        $this->_productsFactory = $productsFactory;
        parent::__construct($context, $data);
    }

    /**
     * Getting most viewed products
     */
    public function getCollection()
    {

        $currentStoreId = $this->_storeManager->getStore()->getId();

        $collection = $this->_productsFactory->create()
        ->addAttributeToSelect(
            '*'
        )->addViewsCount()->setStoreId(
                $currentStoreId
        )->addStoreFilter(
                $currentStoreId
        );
        $items = $collection->getItems();
        return $items;
    }

}

mostProduct.phtml

<?php  $mostCollection =  $block->getCollection();

echo $mostCollection->count();
?>

I din't get product how i get most view products

How to get all coustmer products wishlist collection

Best Answer

Here's an example to show how to get these collections:

<?php


namespace Vendor\Module\Block;


use Magento\Framework\View\Element\Template;

class Statistics extends Template
{
    protected $bestSellerCollection;
    protected $mostViewedCollection;
    protected $wishListHelper;

    public function __construct(
        Template\Context $context,
        \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $bestSellerCollectionFactory,
        \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $mostViewedCollectionFactory,
        \Magento\Wishlist\Helper\Data $wishListHelper,
        array $data = []
    ) {
        $this->bestSellerCollection = $bestSellerCollectionFactory->create();
        $this->mostViewedCollection = $mostViewedCollectionFactory->create();
        $this->wishListHelper = $wishListHelper;
        parent::__construct($context, $data);
    }

    public function getBestSellers()
    {
        $this->bestSellerCollection->setModel('Magento\Catalog\Model\Product')
            ->addStoreFilter($this->_storeManager->getStore()->getId());

        return $this->bestSellerCollection;
    }

    public function getMostViewed()
    {
        $storeId = $this->_storeManager->getStore()->getId();

        $this->mostViewedCollection->addAttributeToSelect(
            '*'
        )->addViewsCount()->setStoreId(
            $storeId
        )->addStoreFilter(
            $storeId
        );

        return $this->mostViewedCollection;
    }

    public function getWishlist()
    {
        $collection = $this->wishlistHelper->getWishlist()->getCollection();

        return $collection;
    }
}

and for the template:

<div>
    <h2>Best Sellers</h2>
    <ol>
        <?php foreach ($block->getBestSellers() as $item): ?>
            <li><?php echo $item->getProductName(); ?></li>
        <?php endforeach; ?>
    </ol>
</div>

<div>
    <h2>Most Viewed</h2>
    <ol>
        <?php foreach ($block->getMostViewed() as $item): ?>
            <li><?php echo $item->getName(); ?></li>
        <?php endforeach; ?>
    </ol>
</div>

<div>
    <h2>Customer ID > Wishlist items</h2>
    <ul>
        <?php foreach ($block->getWishlist() as $list): ?>
            <li>
                <?php echo $list->getCustomerId(); ?>
                <ul>
                    <?php foreach ($list->getItemCollection() as $item): ?>
                        <li><?php echo $item->getName(); ?></li>
                    <?php endforeach; ?>
                </ul>
            </li>
         <?php endforeach; ?>
    </ul>
</div>

You have to set cacheable="false" in the layout xml for this block in order for the wishlist to work. Otherwise you can get the wishlist items via javascript: JSON.parse(window.localStorage.getItem('mage-cache-storage')).wishlist

Refresh the statistics in the admin panel under 'reports' to update the best seller and most viewed items.