Displaying Recently Viewed Products on Your Magento Homepage
In Magento, displaying recently viewed products can significantly enhance user experience by providing personalized product recommendations based on their browsing history. Here’s how you can achieve this:
Understanding the Recent Products Feature in Magento
Magento’s core functionality allows users to keep track of the last 10 products they’ve viewed. This data is stored in the core/session and the catalog/product_viewed tables. The product.ViewedProducts session variable contains an array of recently viewed product IDs.
Implementing a Recently Viewed Products Block
To display this information on your homepage, you’ll need to create a new block using Magento’s Layout XML system. Here are the steps:
- Open your theme’s
layout/default.xmlfile and add or modify the following code inside the<reference name="content">tag:
<block type="reports/product_viewed" name="recently_viewed_products" template="report/viewed.phtml"/>
-
Create a new file named
viewed.phtmlin your theme’stemplate/report/directory. -
In the
viewed.phtmlfile, you can use the following code to retrieve and display recently viewed products:
<?php
$_helper = Mage::helper('reports');
$products = $_helper->getLastViewedProducts();
?>
<div class="block-recently-viewed">
<h2>Recently Viewed Products</h2>
<?php if (count($products) > 0): ?>
<ul class="list">
<?php foreach ($products as $productId => $productInfo): ?>
<li><a href="<?php echo $this->getProductUrl($productInfo['product_id']) ?>"><?php echo $productInfo['name'] ?></a></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
No recently viewed products.
<?php endif; ?>
</div>
- Save the file.
Displaying the Recently Viewed Products on the homepage
To display this block on your homepage, you need to specify it in the homepage layout handle:
-
Open your theme’s
layout/default.xmlfile and find or add the<reference name="content">tag inside the<default>element. -
Add the following code inside the
<reference name="content">tag:
<block type="reports/product_viewed" name="homepage_recently_viewed_products" template="report/viewed.phtml"/>
- Save the file.
Conclusion
By following these steps, you should now have a working recently viewed products block on your Magento homepage. This feature can be further customized by modifying the CSS and layout of the viewed.phtml template to match your site’s design.
Remember to always backup your files before making any changes, especially in production environments.
For more advanced customizations and best practices for enhancing your Magento 2 store performance, consider reading our comprehensive guide on Optimizing Magento Performance.