見出し画像

[Shopify]アプリを使わず最近見た商品を表示する

メタフェイズではShopifyを利用したストア構築を行っています。
今回は最近見た商品を表示する方法を紹介いたします。



1 下記からzipファイルをダウンロードします。

https://github.com/carolineschnapp/recently-viewed
https://github.com/BorisMoore/jquery-tmpl


2 下記2ファイルをassetsフォルダに配置します。

  • jquery.products.min.js

  • jquery.tmpl.min.js

3 theme.liquidの</body>の直前に下記を追記します。

{% if template.name == "product" %}
{{ '//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js' | script_tag }}
{{ 'jquery.products.min.js' | asset_url | script_tag }}
<script>
Shopify.Products.recordRecentlyViewed();
</script>
{% endif %}

4 snippets/recently-viewed.liquidを下記の内容で作成する

{{ '//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js' | script_tag }}
{{ 'jquery.products.min.js' | asset_url | script_tag }}
{{ 'jquery.tmpl.min.js' | asset_url | script_tag }}

<div id="recently-viewed-products" class="collection clearfix" style="display:none;">
  <h2>Recently Viewed Products</h2>
</div>

{% raw %}
<script id="recently-viewed-product-template"  type="text/x-jquery-tmpl">
<div id="product-${handle}" class="product">
  <div class="image">
    <a href="${url}">
      <img src="${Shopify.Products.resizeImage(featured_image, "medium")}" />
    </a>
  </div>
  <div class="details">
    <a href="${url}">
      <span class="title">${title}</span>
      <span class="price">{{if price_varies}}From {{/if}}${Shopify.formatMoney(price)}</span>
    </a>
  </div>
</div>
</script>
{% endraw %}

<script>
Shopify.Products.showRecentlyViewed( { howManyToShow:4 } );
</script>

5 商品詳細のセクションに下記を追記します。

{% render 'recently-viewed' %}

6 jquery.products.min.jsを修正します。

window.location.pathname.match(/\/products\/([a-z0-9\-]+)/)[1];

window.location.pathname.match(/\/products\/([a-zA-Z0-9\-%\_@]+)/)[1];

へ修正します。

この修正によって商品ハンドルが日本語でも正常に動作するようになります。
また、商品画像が設定されていない商品がある場合エラーが発生して正しく表示されません。


Shopifyを利用したストアの構築・運用のご相談は株式会社メタフェイズまで!

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