FROM CACHE - jp_header
このコミュニティはピアツーピアサポートに移行しました。Shopify サポートは今後、このコミュニティへのサービスを提供いたしません。これからもぜひ、他のマーチャントやパートナーとつながり、サポートし合い、経験を共有してください。 当社の行動規範に違反する行動や削除を希望するコンテンツがありましたら、引き続きご報告ください

JavaScriptを使ってカートでSKUに「-PRT」を含むバリエーションが合計100個以上の時に特定のメッセージをカートに表示するようにしたいです。

解決済

JavaScriptを使ってカートでSKUに「-PRT」を含むバリエーションが合計100個以上の時に特定のメッセージをカートに表示するようにしたいです。

n_ogawa3
遊覧客
28 0 6

Shopifyのプランは「Basic」、テーマは「Rise」を使っています。

 

テーマのコードの直接編集ではなく、テーマのカスタマイズで作成しています。

 

セクションの「カスタムliquid」に以下のコードで、カートでSKUに「-PRT」を含むバリエーションが合計100個以上の時に特定のメッセージをカート上に表示するように設定しました。

 

n_ogawa3_0-1747725445893.png

 

{% comment %} SKUに「-PRT」を含む商品の合計数量を初期化します {% endcomment %}
{%- assign prt_variant_total_quantity = 0 -%}

{% comment %} カート内の各商品をループ処理します {% endcomment %}
{%- for item in cart.items -%}
  {% comment %} SKUに「-PRT」という文字列が含まれているか確認します {% endcomment %}
  {%- if item.variant.sku contains "-PRT" -%}
    {% comment %} 含まれている場合、その商品の数量を合計に加算します {% endcomment %}
    {%- assign prt_variant_total_quantity = prt_variant_total_quantity | plus: item.quantity -%}
  {%- endif -%}
{%- endfor -%}

{% comment %} SKUに「-PRT」を含む商品の合計数量が100以上の場合にメッセージを表示します {% endcomment %}
{%- if prt_variant_total_quantity >= 100 -%}
  <div class="custom-prt-notification" style="padding: 15px; margin-bottom: 20px; border: 1px solid #f0e68c; background-color: #fffacd; text-align: center;">
    <p style="margin: 0; font-size: 1.1em;">
      <strong>※重要なお知らせ※</strong><br><div style="text-align: left;" font-size: 13px; >冊子印刷版を100冊以上購入される場合、お届けまで通常よりもお時間がかかる場合がございます。予めご了承ください。</div>
    </p>
  </div>
{%- endif -%}

 

こちらを、できたらカート内でバリエーションの合計数が更新される度に読み込むようにしたいです。

恐らくJavaScriptが必要になると思うのですが、中々うまくいきません。

 

具体的にどのようにコードを書くといいでしょうか。

ご教示いただけますと幸いです。

 

よろしくお願いいたします。

1 件の受理された解決策

Qcoltd
Shopify Partner
1399 543 518

成功

@n_ogawa3

 

数量が変更された場合でも動くようにjsを追加してみました。

詳しくはチェックをしておりませんので、ご利用の際はチェックを行った上でご利用ください。

 

{%- assign prt_variant_total_quantity = 0 -%}
{%- for item in cart.items -%}
  {%- if item.variant.sku contains "-PRT" -%}
    {%- assign prt_variant_total_quantity = prt_variant_total_quantity | plus: item.quantity -%}
  {%- endif -%}
{%- endfor -%}

<div id="custom-prt-notification"
     class="custom-prt-notification"
     style="padding:15px;margin-bottom:20px;border:1px solid #f0e68c;background:#fffacd;text-align:center;{% unless prt_variant_total_quantity >= 100 %}display:none;{% endunless %}">
  <p style="margin:0;font-size:1.1em;">
    <strong>※重要なお知らせ※</strong><br>
    <span style="font-size:13px;display:inline-block;text-align:left;">
      冊子印刷版を100冊以上購入される場合、お届けまで通常よりもお時間がかかる場合がございます。予めご了承ください。
    </span>
  </p>
</div>

<script>
(function() {
  const SKU_MARK = '-PRT';
  const THRESHOLD = 100;
  const noticeEls = document.querySelectorAll('#custom-prt-notification');

  if (!noticeEls.length || !window.fetch) return;

  function toggleByCart(cart) {
    const total = cart.items.reduce(
      (sum, i) => i.sku?.includes(SKU_MARK) ? sum + i.quantity : sum, 0
    );
    noticeEls.forEach(el => el.style.display = total >= THRESHOLD ? 'block' : 'none');
  }

  function refreshFromCartJS() {
    fetch(`/cart.js?_=${Date.now()}`)
      .then(r => r.json())
      .then(toggleByCart)
      .catch(console.error);
  }

  refreshFromCartJS();

  const origFetch = window.fetch;
  window.fetch = function(resource, init) {
    const isCartAPI = typeof resource === 'string' && resource.startsWith('/cart');
    return origFetch.apply(this, arguments).then(async res => {
      if (isCartAPI) {
        try {
          const clone = res.clone();
          if (clone.headers.get('content-type')?.includes('json')) {
            const data = await clone.json();
            if (data?.items) {
              toggleByCart(data);
              return res;
            }
          }
        } catch(e) {}
        refreshFromCartJS();
      }
      return res;
    });
  };

  (function() {
    const XHR = XMLHttpRequest.prototype;
    const origOpen = XHR.open, origSend = XHR.send;

    XHR.open = function(method, url) {
      this._isCartAPI = typeof url === 'string' && url.startsWith('/cart');
      return origOpen.apply(this, arguments);
    };

    XHR.send = function() {
      if (this._isCartAPI) {
        this.addEventListener('load', () => {
          try {
            const data = JSON.parse(this.responseText);
            if (data?.items) { toggleByCart(data); return; }
          } catch(e) {}
          refreshFromCartJS();
        });
      }
      return origSend.apply(this, arguments);
    };
  })();
})();
</script>

 

ご参考まで。

(キュー小坂)

株式会社Q (キュー)
グラフィックデザイン、アパレル事業、Web制作など色々やっている渋谷区代々木の会社です。ShopifyでのECサイトの運営・開発も行なっています。
私たちについて: https://web.q-co.jp/ テックブログ: https://techlab.q-co.jp/

元の投稿で解決策を見る

2件の返信2

Qcoltd
Shopify Partner
1399 543 518

成功

@n_ogawa3

 

数量が変更された場合でも動くようにjsを追加してみました。

詳しくはチェックをしておりませんので、ご利用の際はチェックを行った上でご利用ください。

 

{%- assign prt_variant_total_quantity = 0 -%}
{%- for item in cart.items -%}
  {%- if item.variant.sku contains "-PRT" -%}
    {%- assign prt_variant_total_quantity = prt_variant_total_quantity | plus: item.quantity -%}
  {%- endif -%}
{%- endfor -%}

<div id="custom-prt-notification"
     class="custom-prt-notification"
     style="padding:15px;margin-bottom:20px;border:1px solid #f0e68c;background:#fffacd;text-align:center;{% unless prt_variant_total_quantity >= 100 %}display:none;{% endunless %}">
  <p style="margin:0;font-size:1.1em;">
    <strong>※重要なお知らせ※</strong><br>
    <span style="font-size:13px;display:inline-block;text-align:left;">
      冊子印刷版を100冊以上購入される場合、お届けまで通常よりもお時間がかかる場合がございます。予めご了承ください。
    </span>
  </p>
</div>

<script>
(function() {
  const SKU_MARK = '-PRT';
  const THRESHOLD = 100;
  const noticeEls = document.querySelectorAll('#custom-prt-notification');

  if (!noticeEls.length || !window.fetch) return;

  function toggleByCart(cart) {
    const total = cart.items.reduce(
      (sum, i) => i.sku?.includes(SKU_MARK) ? sum + i.quantity : sum, 0
    );
    noticeEls.forEach(el => el.style.display = total >= THRESHOLD ? 'block' : 'none');
  }

  function refreshFromCartJS() {
    fetch(`/cart.js?_=${Date.now()}`)
      .then(r => r.json())
      .then(toggleByCart)
      .catch(console.error);
  }

  refreshFromCartJS();

  const origFetch = window.fetch;
  window.fetch = function(resource, init) {
    const isCartAPI = typeof resource === 'string' && resource.startsWith('/cart');
    return origFetch.apply(this, arguments).then(async res => {
      if (isCartAPI) {
        try {
          const clone = res.clone();
          if (clone.headers.get('content-type')?.includes('json')) {
            const data = await clone.json();
            if (data?.items) {
              toggleByCart(data);
              return res;
            }
          }
        } catch(e) {}
        refreshFromCartJS();
      }
      return res;
    });
  };

  (function() {
    const XHR = XMLHttpRequest.prototype;
    const origOpen = XHR.open, origSend = XHR.send;

    XHR.open = function(method, url) {
      this._isCartAPI = typeof url === 'string' && url.startsWith('/cart');
      return origOpen.apply(this, arguments);
    };

    XHR.send = function() {
      if (this._isCartAPI) {
        this.addEventListener('load', () => {
          try {
            const data = JSON.parse(this.responseText);
            if (data?.items) { toggleByCart(data); return; }
          } catch(e) {}
          refreshFromCartJS();
        });
      }
      return origSend.apply(this, arguments);
    };
  })();
})();
</script>

 

ご参考まで。

(キュー小坂)

株式会社Q (キュー)
グラフィックデザイン、アパレル事業、Web制作など色々やっている渋谷区代々木の会社です。ShopifyでのECサイトの運営・開発も行なっています。
私たちについて: https://web.q-co.jp/ テックブログ: https://techlab.q-co.jp/
n_ogawa3
遊覧客
28 0 6

早速ありがとうございます!

試してみたら希望通り動きました!

ありがとうございました。