Liquid、JavaScriptなどに関する質問
Shopifyのプランは「Basic」、テーマは「Rise」を使っています。
テーマのコードの直接編集ではなく、テーマのカスタマイズで作成しています。
セクションの「カスタムliquid」に以下のコードで、カートでSKUに「-PRT」を含むバリエーションが合計100個以上の時に特定のメッセージをカート上に表示するように設定しました。
{% 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が必要になると思うのですが、中々うまくいきません。
具体的にどのようにコードを書くといいでしょうか。
ご教示いただけますと幸いです。
よろしくお願いいたします。
解決済! ベストソリューションを見る。
成功
数量が変更された場合でも動くように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>
ご参考まで。
(キュー小坂)
成功
数量が変更された場合でも動くように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>
ご参考まで。
(キュー小坂)
早速ありがとうございます!
試してみたら希望通り動きました!
ありがとうございました。
いつもShopifyをご利用いただき、ありがとうございます。 Shopifyは、皆様の日本語での利用体験の向上に努めております。さらなる改善のために皆様のご意見をお寄せい...
By JasonH May 9, 2025Shopify アカデミーの学習パスと認定スキルバッジExpanding Your Shopify Business Internationallyを活用して、国際的にビジネ...
By Shopify Feb 7, 2025Shopify アカデミーの学習パスB2B on Shopify:立ち上げとカスタマイズで卸売販売に進出しましょう。これら3つの無料コースは、ShopifyストアでB2B機能...
By Shopify Jan 31, 2025