Table of Contents
- Introduction
- Why Show Recently Viewed Products?
- Step-by-Step Process to Fetch Recently Viewed Products
- Troubleshooting Common Issues
- Conclusion
- FAQ
Introduction
Have you ever wondered how to enhance the user experience on your Magento 2.2.2 e-commerce site? Showing customers their recently viewed products can significantly improve engagement and conversion rates. This blog post will guide you on how to fetch recently viewed products programmatically in Magento 2.2.2, providing you with actionable steps and insights that make this feature easy to implement.
Understanding how to programmatically retrieve recently viewed products can be incredibly beneficial, especially when custom functionality is needed beyond Magento's default capabilities. By the end of this article, you will be able to implement code snippets to get recently viewed products and understand how this can be customized according to your business needs.
We will cover:
- Why showing recently viewed products is important.
- The step-by-step process of fetching recently viewed products in Magento 2.2.2.
- Troubleshooting common issues.
Let's dive in!
Why Show Recently Viewed Products?
Displaying recently viewed products can dramatically improve user engagement and increase sales. This feature serves as a reminder of products users have shown interest in, making it easier for them to revisit and potentially purchase those items. Here are some key benefits:
- Enhanced User Experience: It simplifies the shopping process by allowing users to quickly navigate back to products they've recently viewed.
- Increased Conversion Rates: The more a user sees a product, the higher the likelihood they will buy it.
- Personalized Shopping: Offering a personalized shopping experience increases customer satisfaction.
Given these benefits, integrating this feature into your Magento store can be a game changer.
Step-by-Step Process to Fetch Recently Viewed Products
1. Requirements and Setup
Before diving into the code, ensure you have these prerequisites:
- Magento 2.2.2 installed and running.
- Basic understanding of Magento module and template files.
- Access to your Magento project’s filesystem to add or modify files.
2. Code Implementation
To fetch recently viewed products, you need to import certain classes and use predefined methods provided by Magento. Below is a step-by-step guide to implementing this feature:
a. Create a New Block
First, create a new block file where your custom code will reside.
// app/code/YourNamespace/YourModule/Block/RecentlyViewed.php
namespace YourNamespace\YourModule\Block;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Reports\Model\ResourceModel\Product\CollectionFactory as ReportCollectionFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Data\Helper\PostHelper;
class RecentlyViewed extends AbstractProduct
{
protected $_reportCollectionFactory;
protected $_productRepository;
protected $_postDataHelper;
protected $_customerSession;
protected $_catalogSession;
public function __construct(
\Magento\Catalog\Block\Product\Context $context,
ReportCollectionFactory $reportCollectionFactory,
ProductRepositoryInterface $productRepository,
PostHelper $postDataHelper,
\Magento\Customer\Model\Session $customerSession,
\Magento\Catalog\Model\Session $catalogSession,
array $data = []
) {
$this->_reportCollectionFactory = $reportCollectionFactory;
$this->_productRepository = $productRepository;
$this->_postDataHelper = $postDataHelper;
$this->_customerSession = $customerSession;
$this->_catalogSession = $catalogSession;
parent::__construct($context, $data);
}
public function getRecentProducts($limit = 5)
{
$products = [];
$collection = $this->_reportCollectionFactory->create()
->addAttributeToSelect('*')
->setPageSize($limit)
->setCurPage(1);
foreach ($collection as $product) {
$products[] = $this->_productRepository->getById($product->getId());
}
return $products;
}
}
b. Create a New Template File
Create a new template file to display the recently viewed products.
<!-- app/code/YourNamespace/YourModule/view/frontend/templates/recently_viewed.phtml -->
<?php
$products = $block->getRecentProducts();
?>
<div class="recently-viewed-products">
<h2>Recently Viewed Products</h2>
<ul>
<?php foreach ($products as $product): ?>
<li>
<a href="<?= $product->getProductUrl() ?>">
<img src="<?= $block->getImage($product, 'category_page_list')->getImageUrl() ?>" alt="<?= $product->getName() ?>">
<p><?= $product->getName() ?></p>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
c. Update the Layout File
Finally, update the layout XML to add the block to your desired page.
<!-- app/code/YourNamespace/YourModule/view/frontend/layout/catalog_product_view.xml -->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="YourNamespace\YourModule\Block\RecentlyViewed" name="recently.viewed.products" template="YourNamespace_YourModule::recently_viewed.phtml"/>
</referenceContainer>
</body>
</page>
3. Customization Tips
You can customize the appearance and functionality of recently viewed products using the following tips:
-
Adjust the Products Count: In the
getRecentProductsmethod, modify the$limitparameter to show more or fewer products. - Styling: Use CSS to style the product list as needed. This will enhance the user interface, making it more visually appealing.
- Conditional Logic: Implement conditional logic to check user sessions or specific conditions before displaying the block.
Troubleshooting Common Issues
Despite following the steps, you might encounter some issues. Here’s how to troubleshoot common problems:
-
Products Not Showing: Ensure Full Page Cache is disabled or configure the custom block to be non-cacheable:
<block class="YourNamespace\YourModule\Block\RecentlyViewed" cacheable="false" .../> - Dependency Injection Errors: Verify that all required dependencies are injected correctly in the block constructor.
-
Magento Cache: Clear Magento cache after making any configuration changes to ensure the updates are applied:
bin/magento cache:clean && bin/magento cache:flush
Conclusion
Integrating a recently viewed products feature in Magento 2.2.2 can significantly enhance your e-commerce site’s user experience and boost sales. By following the steps outlined in this guide, you can programmatically fetch and display recently viewed products, offering your customers a more personalized and engaging shopping journey.
Stay tuned for more insights and tips on optimizing and customizing your Magento store for an enriched customer experience.
FAQ
Q1: Can recently viewed products be cached?
- Yes, but it might not always reflect real-time data. To ensure accuracy, set the block to be non-cacheable.
Q2: How can I limit the number of recently viewed products displayed?
- Modify the
$limitparameter in thegetRecentProductsmethod within the block class.
Q3: Is it possible to display the recently viewed products on multiple pages?
- Yes, by adding the block to the relevant layout XML files of those pages.
Q4: Does this feature require any additional extensions?
- No, this can be achieved with built-in Magento functionalities and custom coding as described in this guide.
Implement this today and witness an improvement in your Magento store’s user interaction and conversion rates!