【Shopify】アプリなしでSALE時の割引率を表示する!

PRYTHMWORKS Shopify
Shopify

割引率の表示はこのコードで完了!

{% if current_variant.compare_at_price > 0 %}
  {% comment %}割引前価格が設定されていればOFF率表記自体する{% endcomment %}
  {% assign float_compare_at_price = current_variant.compare_at_price | times: 1.0 %} 
  {% assign per_sale = current_variant.price |  divided_by: float_compare_at_price %}
  {% assign float_per_off = 1 | minus: per_sale %}
  {% assign per_off = float_per_off | times: 100  | round %}            
  <span style="
    background: #ee7676;
    color: #fff;
    padding: 0 3px;">{{ per_off }}%OFF</span>
{% endif %}

コードの解説

{% if current_variant.compare_at_price > 0 %}

ここの条件式で、current_variant.compare_at_price(現在選択しているバリエーションに割引前価格)があるか?

を判別しています。

存在していれば0より大きいので、if文の中の処理が実行されます。

{% assign float_compare_at_price = current_variant.compare_at_price | times: 1.0 %} 

①・・・float_compare_at_priceと名付ける変数に、current_variant.compare_at_price(現在選択している商品のバリエーションの割引前価格)に1.0掛けた数値を代入。

仮に、

販売価格が900円で、割引前価格が1,000円とする。→出てほしい割引率表記は「10%」

{% assign per_sale = current_variant.price |  divided_by: float_compare_at_price %}

②・・・per_saleと名付ける変数に、current_variant.price(現在選択している商品のバリエーションの販売価格)を①で宣言したfloat_compare_at_price変数の数値で割った数を代入。

仮の例で計算するなら、

900 ÷ 1000 = 0.9

per_sale変数には0.9が代入される。

{% assign float_per_off = 1 | minus: per_sale %}

③・・・float_per_offと名付ける変数に、1マイナス②で宣言したper_sale変数の数値を代入。

仮の例で計算するなら、

1 - 0.9 = 0.1

float_per_off変数に0.1(つまり10%)が代入される。

{% assign per_off = float_per_off | times: 100  | round %} 

④・・・per_offと名付ける変数に、③で宣言したfloat_per_off変数の数値を100倍して、かつ小数点がでたとき、もっとも近い整数に丸める。

仮の例で計算するなら、

0.1 × 100 = 10

 <span style="
    background: #ee7676;
    color: #fff;
    padding: 0 3px;">{{ per_off }}%OFF</span>

⑤最後に、HTMLタグの中に④で宣言したper_off変数を{{ }}で出力。

これで割引率が、「10%OFF」と表示されます。

ラベル形や色は、お好みでcssでデザインしてください。

(補足)Shopifyチートシートの紹介

Shopifyで使用されるliquidテンプレートやオブジェクト名、オブジェクトのプロパティ名を即確認する際はここが便利です!

Shopify Cheat Sheet

Shopify Cheat Sheet — A resource for building Shopify Themes with Liquid
This cheat sheet is an interactive reference for the Liquid templating language that will help you build ecommerce templates on Shopify.
タイトルとURLをコピーしました