edo1z blog

プログラミングなどに関するブログです

Shopify - 特定の商品を購入している場合にのみ閲覧可能なページを作成する

特定の商品を購入している場合にのみ、閲覧可能なページを作成したい場合は下記のようにやるととりあえず出来ました。

前提

  • 対象となる特定商品の商品のハンドルに、「hoge」という文字列が存在する。
  • 対象外の商品のハンドルには、「hoge」という文字列は存在しない。

方法案

  • 作成するページ専用のテンプレートを作成し、テンプレートのコードを下記のようにする。
{% if customer %}
  {% if customer.orders.size != 0 %}
    {% for order in customer.orders %}
      {% for line_item in order.line_items %}
        {% if line_item.product.handle contains 'hoge' %}
          {% assign hasProduct = true %}
        {% endif %}
      {% endfor %}
    {% endfor %}
  {% endif %}
{% endif %}
{% if hasProduct %}
  {{ page.content }}
{% else %}
  <script>location.href="/"</script>
{% endif %}