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

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

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

n_ogawa3
遊覧客
28 0 6

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

 

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

 

こちらで回答いただいたものの別バージョンです。

 

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

 

n_ogawa3_0-1747755956095.png

 

{% comment %} ----- SKUに「-PRT」を含む商品が存在するかどうかをチェックします ----- {% endcomment %}
{%- assign prt_variant_in_cart = false -%}
{%- for item in cart.items -%}
  {% comment %} 現在の商品のSKUに「-PRT」という文字列が含まれているか確認します {% endcomment %}
  {%- if item.variant.sku contains "-PRT" -%}
    {% comment %} 「-PRT」を含む商品が見つかった場合、フラグをtrueに設定し、ループを終了します {% endcomment %}
    {%- assign prt_variant_in_cart = true -%}
    {%- break -%}
  {%- endif -%}
{%- endfor -%}

{% comment %} ----- 「-PRT」SKU商品が存在する場合にメッセージを表示します ----- {% endcomment %}
{%- if prt_variant_in_cart -%}
  <div class="cart-custom-info prt-sku-info" style="background-color: #fff0f5; color: #db7093; border: 1px solid #ffe4e1; padding: 15px; margin: 15px 0; text-align: center; border-radius: 4px;">
    <p style="margin: 0; font-weight: 500;">
      <strong>【冊子印刷版をご注文のお客様へ】</strong><br>
<div style="text-align: left;" font-size: 13px; >
※注文をお受けしてから製本するオンデマンド製本方式を採用しております。<br>
※そのため、ご注文とお支払い確認後、4営業日程での発送となります。
<div>
    </p>
  </div>
{%- endif -%}

 

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

JavaScriptが必要になると思うのですが、こちらを参考にしようと思いましたが、私が素人なので中々うまくいきません。

 

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

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

 

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

 

1件の返信1

Qcoltd
Shopify Partner
1410 546 523

@n_ogawa3 様

 

こちらのページで回答した内容に今回のご質問内容をマージしてみました。

実際にコードを動かしてはおりませんので、実際に使用される場合は、ご確認の上ご利用ください。

 

参考コード

{%- comment -%} PRT SKU数量計算 {%- endcomment -%}
{%- 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 -%}

{%- comment -%} 100冊以上のアラート表示 {%- endcomment -%}
<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>

{%- comment -%} PRT SKUの存在確認 {%- endcomment -%}
<div id="prt-warning" style="display:{% if prt_variant_total_quantity > 0 %}block{% else %}none{% endif %}; background-color:#fff0f5; color:#db7093; border:1px solid #ffe4e1; padding:15px; margin:15px 0; text-align:center; border-radius:4px;">
  <p style="margin:0; font-weight:500;">
    <strong>【冊子印刷版をご注文のお客様へ】</strong><br>
    <div style="text-align:left; font-size:13px;">
      ※注文をお受けしてから製本するオンデマンド製本方式を採用しております。<br>
      ※そのため、ご注文とお支払い確認後、4営業日程での発送となります。
    </div>
  </p>
</div>

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

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

  function checkCart(cart) {
    let total = 0;
    let foundPRT = false;
    cart.items.forEach(i => {
      if (i.sku?.includes(SKU_MARK)) {
        total += i.quantity;
        foundPRT = true;
      }
    });

    // 100冊超え通知
    noticeEls.forEach(el => el.style.display = total >= THRESHOLD ? 'block' : 'none');

    // PRT存在通知
    infoEls.forEach(el => el.style.display = foundPRT ? 'block' : 'none');
  }

  function refreshFromCartJS() {
    fetch(`/cart.js?_=${Date.now()}`)
      .then(r => r.json())
      .then(checkCart)
      .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) {
              checkCart(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) { checkCart(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/