To do this programmatically, you need the collection function to get called in custom phtml file so that the product will be shown in the file.
Let’s say we have a module which is named “Magemonkeys_Recentlyview”
For that module, we have to create a block file Recentlyview.php at app/code/Magemonkeys/Recentlyview/Block/
namespace MagemonkeysRecentlyviewBlock;
class Recentlyview extends MagentoFrameworkViewElementTemplate
{
protected $recentlyView;
public function __construct(
MagentoFrameworkViewElementTemplateContext $context,
MagentoReportsBlockProductViewed $recentlyView,
array $data = []
) {
$this->recentlyView = $recentlyView;
parent::__construct($context, $data);
}
public function getRecentviewCollection()
{
return $this->recentlyView->getItemsCollection()->load();
}
}
Now we can call that block function in custom phtml file
create app/code/Magemonkeys/Recentlyview/view/recentlyview.html file
$productviewcollection = $this->getRecentviewCollection();
foreach ($productviewcollection as $recentlyview)
{
echo $recentlyview->getName();
}
Now check the result by clearing the cache.

