star back image
people4
電飾 電飾
moon
men
shopifyバリエーションに在庫数を出したい

【shopify】商品のバリエーションに在庫数を出したい

BLOG shopifyWEBログ
読了約:6分

購入しようとカートボタンを押す前に、サイズなどのバリエーションを選択をする機会があります。

サイズ選択のプルダウンの画像。在庫数が表示されている図。

上の画像のように、LサイズMサイズの横に、在庫の残りの数が表示されているのを、稀に見ることがあります。

XSの残りが1ですよ!

どうやるのでしょう。検索したところ公式ヘルプにありました。

shopify公式ヘルプ
https://help.shopify.com/ja/manual/online-store/themes/themes-by-shopify/vintage-themes/customizing-vintage-themes/show-remaining-quantity

ヘルプには沢山の記述がありよくわかりません。しかし、バリエーションごとの在庫数は、variant.inventory_quantityを使って取得するようです。

shopifyのバージョンで対応方法が違う?
AIさんに聞くしかないな。。

以下メモ&サンプルコードになります。

【共有】liquidソースコード

{% for value in option.values %}
  {% assign variant = product.variants | where: 'option{{ option.position }}', value | first %}
  <button @click="optionChange($el)" data-single-option-selector="" data-position="{{ option.position }}" type="button" role="option" value="{{ value | escape }}" :aria-selected="option{{ option.position }} === $el.value ? 'true' : null" class="variant-dropdown-button break-word block bg-scheme-background px-4 py-2 text-left text-scheme-text hover:text-scheme-accent focus-visible:text-scheme-accent aria-selected:text-scheme-accent coarse-pointer:min-h-[44px] coarse-pointer:min-w-[44px] {% if variant.inventory_quantity == 0 %} sold-out {% endif %}">
    {{ value }}
    {% if variant.inventory_quantity > 3 %}
      - 残り {{ variant.inventory_quantity }}
    {% elsif variant.inventory_quantity > 0 %}
      - 在庫わずか
    {% else %}
      - 在庫なし
    {% endif %}
  </button>
{% endfor %}

テーマテンプレートによってliquidコードの記述が多少変わると思いますが、プルダウンの中の内容は{% for value in option.values %}のループ内で、<button>に{{ value }}を吐き出しておりますソースのところまで移動します。

ソースコードの4行目、
{{ value }}は、SとかMとかLとかXXLなどのテキストが入るものです。

{{ value }}
{% if variant.inventory_quantity > 3 %}
- 残り {{ variant.inventory_quantity }}
{% elsif variant.inventory_quantity > 0 %}
- 在庫わずか
{% else %}
- 在庫なし
{% endif %}

{{ value }}の下に、variant.inventory_quantityを使ってif文を仕込んでいただければ在庫数の表示がバッチリ出力されました。

※ifの内容補足

  • variant.inventory_quantity > 3 の在庫数が4個以上の場合:在庫数を表示。
  • variant.inventory_quantity > 0 の在庫数が3個以下の場合:在庫わずかと表示。
  • 在庫がない場合:在庫なし と表示。

バリエーションの選択は、プルダウンでなくボタンタイプもあると思います。

それでも基本forループがあって、{{ value }}が吐き出されておりますところに、同様に適用すると実現可能だと思います。

I wish you good luck.

星間旅路のメロディ

「宇宙の静けさに包まれながら、漂流する過去の音楽を捜し求め、銀河の奥底でその旋律に耳を傾ける。」

「この電波はどこの星からきたのだろうか。」