I have got the error below:
Error: Call to undefined method Magento\Catalog\Model\ResourceModel\Product\Collection\Interceptor::addViewsCount()
<?php
namespace Vendor\Mostviewed\Block;
class Mostviewed extends \Magento\Catalog\Block\Product\AbstractProduct
{
protected $_filesystem ;
protected $_imageFactory;
protected $_productCollectionFactory;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
\Magento\Framework\Filesystem $filesystem,
\Magento\Framework\Image\AdapterFactory $imageFactory,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
) {
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
/**
* Get Product Collection of MostViewed Products
* @return mixed
*/
public function getMostViewProductCollection()
{
$currentStoreId = $this->_storeManager->getStore()->getId();
// get today and last 30 days time
$today = time();
$last = $today - (60*60*24*30);
$from = date("Y-m-d", $last);
$to = date("Y-m-d", $today);
$collection = $this->_productCollectionFactory->create()
->addAttributeToSelect(
'*'
)->addViewsCount()->setStoreId(
$currentStoreId
)->addStoreFilter(
$currentStoreId
)->setPageSize(10);
$items = $collection->getItems();
//var_dump($items);
return $items;
}
// pass imagename, width and height
public function resize($image, $width = null, $height = null)
{
$absolutePath = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('custom_module/posts/').$image;
if (!file_exists($absolutePath)) return false;
$imageResized = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('resized/'.$width.'/').$image;
if (!file_exists($imageResized)) { // Only resize image if not already exists.
//create image factory...
$imageResize = $this->_imageFactory->create();
$imageResize->open($absolutePath);
$imageResize->constrainOnly(TRUE);
$imageResize->keepTransparency(TRUE);
$imageResize->keepFrame(FALSE);
$imageResize->keepAspectRatio(TRUE);
$imageResize->resize($width,$height);
//destination folder
$destination = $imageResized ;
//save image
$imageResize->save($destination);
}
$resizedURL = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).'resized/'.$width.'/'.$image;
return $resizedURL;
}
}
I want to get the most-view product collection. Please help me in this.