Recently Viewed Products
This section provides an overview of Recently Viewed Products.
Step 1: Create a Snippet
- In your Shopify admin, go to Online Store > Themes.
- Click on Actions > Edit code.
- Under the Snippets folder, click Add a new snippet and name it recently-viewed-products.
Step 2: Add JavaScript to the Snippet
Add the following code to the recently-viewed-products.liquid snippet:
<script>
document.addEventListener('DOMContentLoaded', function() {
var product = {
id: '{{ product.id }}',
title: '{{ product.title }}',
url: '{{ product.url }}',
image: '{{ product.featured_image | img_url: 'small' }}'
};
var recentlyViewed = JSON.parse(localStorage.getItem('recentlyViewed')) || [];
recentlyViewed = recentlyViewed.filter(function(item) {
return item.id !== product.id;
});
recentlyViewed.unshift(product);
if (recentlyViewed.length > 5) {
recentlyViewed.pop();
}
localStorage.setItem('recentlyViewed', JSON.stringify(recentlyViewed));
var recentlyViewedContainer = document.getElementById('recently-viewed-products');
if (recentlyViewedContainer) {
recentlyViewedContainer.innerHTML = recentlyViewed.map(function(item) {
return `
<div class="recently-viewed-item">
<a href="${item.url}">
<img src="${item.image}" alt="${item.title}">
<p>${item.title}</p>
</a>
</div>
`;
}).join('');
}
});
</script>
Step 3: Add the Snippet to Your Product Template
- In the Sections folder, open the product-template.liquid file.
- Add the following code where you want the "Recently Viewed Products" section to appear:
<div id="recently-viewed-products"></div>
{% include 'recently-viewed-products' %}
Step 4: Style the Recently Viewed Products Section
Add some CSS to style the "Recently Viewed Products" section. You can add this to your theme's CSS file:
.recently-viewed-item {
display: inline-block;
margin: 10px;
text-align: center;
}
.recently-viewed-item img {
max-width: 100px;
height: auto;
}