見出し画像

【Shopify構築】コピペで出来る!「最近見た商品」を自動表示させるセクション作成方法 Liquid言語

この記事ではユーザが最近見た商品を自動で表示させるセクションの作成方法を説明します。コードがわからない方でもコピペで簡単に出来ます!
(作業時間約10分程度)

有料アプリを使って「最近見た商品を表示」させることが可能ですが、コードを編集して無料で実装できるのでぜひご参考に!
例では無料テーマのDawnを使用しました。

<仕様>(イメージ画像はページ下部掲載)
最後に見た4つの商品を商品ページに表示
レスポンシブ対応(画面サイズが750px以下になると4列から1列)
タイトルを変更したい場合は、「最近見た商品」のテキストをご変更ください。

1.新しいスニペットを追加して下記コードをコピペする

Shopify管理画面>テーマ>コードを編集
snippetsフォルダに「新しいスニペットを追加する」を選択して
ファイル名は「recently-viewed.liquid」と入力し、下記コードをコピペして保存。

▼コピペするコード

<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);
}
}


.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: 100%;
  width: 100%;
  object-fit: cover;
}

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

.c-product h3.c-product__title {
    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>最近見た商品</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>

2.テンプレファイルに下記コードを追記する

sectionsフォルダにある「main-product.liquid」(Dawnテーマの場合のファイル名称)を開き、追記するコードを入力。

追記する場所は
{% render 'product-media-modal', variant_images: variant_images %}の直後。

※product-media-modalで検索すると見つけやすいです。

▼追記するコード(1行だけ)

  {% render 'recently-viewed' %}


実装イメージ)

PC表示


モバイル表示


以上、ご覧いただきありがとうございました✨
ご質問はXのDMでどうぞ!

海外ノマドをしながらWebデザイナーとして活動しています🌏
良ければXのフォローもよろしくお願いします!


この記事が気に入ったらサポートをしてみませんか?