I am trying to fetch recently viewed products.
I tried to implement the provided code from here but did not get any success.
I am trying to fetch recently viewed products.
I tried to implement the provided code from here but did not get any success.
Try below code in your template file for get recently viewed products in any place,
<?php echo $this->getLayout()
->createBlock("Magento\Reports\Block\Product\Widget\Viewed")
->setDisplayType("recently.view.products")
->setProductsCount("6")
->setTemplate("widget/viewed/content/viewed_list.phtml")
->toHtml();
?>
You can change setProductsCount()
as you need.
With this custom code, you can also get a most viewed products
public function __construct(
\Magento\Reports\Model\ResourceModel\Product\CollectionFactory $reportCollectionFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager
){
$this->reportCollectionFactory = $reportCollectionFactory;
$this->storeManager = $storeManager;
}
public function getMostViewedProducts()
{
$storeId = $this->storeManager->getStore()->getId();
$collection = $this->reportCollectionFactory->create()
->addAttributeToSelect(
'*'
)->addViewsCount()->setStoreId(
$storeId
)->addStoreFilter(
$storeId
);
$items = $collection->getItems();
return $items;
}
You can get recently view product by below code
protected $recentlyViewed;
public function __construct(
...
\Magento\Reports\Block\Product\Viewed $recentlyViewed
) {
...
$this->recentlyViewed = $recentlyViewed;
}
/**
* Get recently viewed products for the customer
*
*/
public function getMostRecentlyViewed(){
return $this->recentlyViewed->getItemsCollection();
}
protected $recentlyViewed;
public function __construct(
...
\Magento\Reports\Block\Product\Viewed $recentlyViewed
) {
...
$this->recentlyViewed = $recentlyViewed;
}
/**
* Get recently viewed products for the customer
*
*/
public function getMostRecentlyViewed(){
return $this->recentlyViewed->getItemsCollection();
}
This code is working and it'll return according to customer session.
If you disabled Full Page cache then it'll display recently viewed prdocuts.
You need to set cacheable="false" for custom block. Please let me know if you still face same issue.