How to Add a Recently Viewed Product Section In Shopify?

How to Add a Recently Viewed Products Section In Shopify?

In the world of e-commerce, enhancing user experience is key to boosting sales and customer satisfaction. One effective way to achieve this is by adding a “Recently Viewed Products” section to your online Shopify store. While many premium Shopify themes include this feature, it’s not readily available in free themes. In this blog post, we’ll show you how to set up a “Recently Viewed Products” section on free Shopify themes like Dawn, Fresh, and Sales.

Why Add a “Recently Viewed Products” Section?

Before we dive into the how-to, you might be wondering why you should consider adding this section to your store. While you may already have a “You May Also Like” section and other features, a “Recently Viewed Products” section is valuable for several reasons:

  1. Facilitating Purchase Decisions: It’s common for online shoppers to take some time before making a purchase decision. Having a section that displays the products they’ve recently viewed keeps those items top of mind.
  2. User Convenience: Customers can easily return to products they are interested in without having to search for them again.
  3. Enhanced User Experience: This feature adds a level of personalization to your store, making it more engaging for users.

Now, let’s go step by step and see how you can implement this feature in your store.

Step 1: Creating a “Recently Viewed” Snippet

To begin, you’ll need to create a “Recently Viewed” snippet. Here’s how:

  1. Log in to your Shopify admin and go to the “Themes” section.
  2. Click on the “Edit Code” option.
  3. Scroll down and open the “Snippets” folder.
  4. Click on “Add a new snippet” and name it “recently-viewed.liquid”

Now, you’re ready for the next step.

Step 2: Adding the Code

<style>
    @media only screen and (min-width: 750px)
{ 
.js-recentPdpBlock{
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  column-gap: var(--grid-desktop-horizontal-spacing);
}
}

@media only screen and (max-width: 576px)
{
    /* Code by https://websensepro.com */
  .js-recentPdpBlock{
  display: grid;
  grid-template-columns: 1fr 1fr;
  column-gap: var(--grid-desktop-horizontal-spacing);
}
  .c-product img{
height: 230px !important;
  }
}

.recently-title h2 {
    font-size: 24px;
    border-top: 1px solid #d2d2d2;
    padding-top: 50px;
}
/* .js-recentPdpBlock {
    display: flex;
    flex-wrap: wrap !important;
} */

.c-product{
  cursor: pointer;
}

.c-product img {
    height: 280px;
  width: 100%;
  object-fit: cover;
}

.c-product p.c-productPrice {
    line-height: 0px;
  color: #000;
}

.c-product h3.c-product__title {
    line-height: 0px;
    padding-bottom: 10px;
}

.c-product h3.c-product__title a {
    color: black;
  text-decoration: none;
}
 a.c-product__url{
    position: relative;
  }
</style>
<script>
    // First Block
        function setRecentlyViewedPdp() {
            const pdpData = {
                productTitle : "{{ product.title }}",
                productImg : "{{ product.featured_image | img_url: '' }}",
                productPrice : "{{ product.price | money | remove_first: '' }}",
                productUrl : "{{ product.url }}"
            };
    
            // Init Empty Array to push data
            const productArr = [];
            // Create a couple of variables 
            let jsonResp,
                jsonRespArr, 
                jsonRespArrStr; 
            // Set the number how many products you want to capture 
            const numberOfProduct = 4;
            // Now push the pdpData into Array so that we can use it 
            productArr.push(pdpData);
            // Get the product title from pdpData 
            const currPdpTitle = pdpData.productTitle;
            // Now Convert current page data into Strings which we already pushed in Array 
            const pdpDataString = JSON.stringify(productArr);
            // Set the variable for localStorage 
            const localData = localStorage.getItem('recently_viewed');
          
            // Second Block
            // first we need to check data if data is not there then store right // away 
            if (localData == null) {
                localStorage.setItem('recently_viewed', pdpDataString);
                
            }
            // If data is there then we need to check couple of other conditions 
            else if ( localData != null ) {
                
                // Create Variable for oldData or Previous page 
                const oldPdpData = localStorage.getItem('recently_viewed');
                // Count the amount of data stored in strings so that we can remove // old products from the stack 
                const countPdpData = (oldPdpData.match(/productTitle/g) || []).length;
                // we also need to check if user is not visiting page again 
                const reVisitPdp =  oldPdpData.includes(currPdpTitle);
                // Get old data, merged it with new data and store merged data
                if (countPdpData < numberOfProduct && reVisitPdp == false) {
                    jsonResp = JSON.parse(oldPdpData);
                    jsonRespArr = jsonResp.concat(productArr);
                    jsonRespArrStr = JSON.stringify(jsonRespArr);
                    localStorage.setItem('recently_viewed', jsonRespArrStr);
                }
                // If User visited more the 4 pages delete first page data 
                else if (countPdpData >= numberOfProduct && reVisitPdp == false) {
                    jsonResp = JSON.parse(oldPdpData);
                    jsonResp.shift();
                    jsonRespArr = jsonResp.concat(productArr);
                    jsonRespArr =  JSON.stringify(jsonRespArr);
                    localStorage.setItem('recently_viewed', jsonRespArr);
                }
            }
        }
        
        // Now we write all our function and it's time to execute it 
        setRecentlyViewedPdp();
        // Set Variable for Local Storage Data 
        const localViewed = localStorage.recently_viewed;
        // console.log to verify the data 
    </script>
             <div class="recently-title">
                      <h2 class="title inline-richtext h2 scroll-trigger animate--slide-in"><b>Recently Viewed</b></h2>
                    </div>
    <div class="js-recentPdpBlock">
    </div>
    <script>
        // Third Block
        function getRecentPdp (){
    
            // First let's convert localStorage data into object again
            const pdpData = JSON.parse(localStorage.getItem('recently_viewed'));
            console.log(pdpData)
            // Create a empty Array
            const recentViewHtml = []
            // Loop through all the data and inject into HTML using ES6
            pdpData.forEach(function(item){ 
                recentViewHtml.push(`
                    <section id="Recent">
                    <div class="c-product">
                        <div class="c-product__img">
                        <a href="${item.productUrl}"><img src='${item.productImg}'/></a>
                        </div>
                        <h3 class="c-product__title">
                            <a class="c-product__url" href="${item.productUrl}">
                            ${item.productTitle}
                            </a>
                        </h3>
                        <p class="c-productPrice">${item.productPrice}</p>
                    </div>
                    
                    
                    </section>
                `)
            })
            // Now consolidate the data 
            const recentBlock = `${recentViewHtml.join('')}`
            // console.log() to check data is correct 
            console.log(recentBlock);
            // Inject into PDP page
            const contentBlock = document.querySelectorAll('.js-recentPdpBlock');
            // Push the data
            contentBlock.forEach(element =>{
                element.innerHTML = recentBlock;
            })
           
        }
        // Execute this function on DOM content load 
    
        getRecentPdp();
        </script>

This code will pull product information from Shopify and utilize local storage in the visitor’s browser to display recently viewed products. The code is designed to work with various Shopify themes.

Step 3: Rendering the Snippet

In the “main-product. liquid” file, search for “product-media-model” and add a line break to render the “recently-viewed” snippet. This step ensures that the recently viewed products appear on your product pages.

{% render 'recently-viewed' %}

Step 4: Test Your “Recently Viewed” Section

Preview your store to ensure that the “Recently Viewed Products” section is functioning correctly. It should display a list of the products a visitor has recently viewed, even after refreshing the page.

4.6/5 - (19 votes)

About

Leave a Comment

Your email address will not be published. Required fields are marked *