Skip to content

Instantly share code, notes, and snippets.

@ellie250
Created May 15, 2026 15:46
Show Gist options
  • Select an option

  • Save ellie250/0312d9db2da3f09ab10071b096ab9ed6 to your computer and use it in GitHub Desktop.

Select an option

Save ellie250/0312d9db2da3f09ab10071b096ab9ed6 to your computer and use it in GitHub Desktop.
{% comment %}
=============================================================================
Simple Bundles — Dynamic PDP Pricing
=============================================================================
Shows a live bundle total on the product page that updates as the customer
changes options.
ACTIVATION RULE
---------------
This snippet only runs on bundles that have **Dynamic Pricing enabled** in
the Simple Bundles app. For any other product (regular products, or bundles
with dynamic pricing turned off), the snippet emits nothing and the page is
completely untouched — Shopify's default price displays as normal.
Dynamic Pricing is detected by checking for the presence of the
`bundle_custom_prices_selection` metafield. The Simple Bundles app only
creates this metafield when Dynamic Pricing is toggled ON in the bundle
settings.
When Dynamic Pricing is on, the metafield value is the single source of truth
for the bundle's price — it reflects either the merchant's custom per-option
prices, or the default product-derived prices, depending on what they've set
up in the app. Either way it matches what Shopify will charge.
THEME COMPATIBILITY
-------------------
Works out of the box on the most popular Shopify themes via a built-in list
of common price selectors. If your theme uses a custom price selector, append
it to `extra_price_selectors` below.
=============================================================================
{% endcomment %}
{%- comment -%} Add any theme-specific selectors here (comma-separated). Leave blank for most themes. {%- endcomment -%}
{%- assign extra_price_selectors = '' -%}
{%- comment -%}
Default selectors covering common Shopify themes:
.product__price → Dawn, Sense, Craft, Studio, Crave, Refresh
.product-price → Minimog, Impulse, Prestige, many custom themes
.product-single__price → Older Shopify themes (Brooklyn, Debut, Narrative)
.product__info-price → Symmetry, some Archetype themes
.price--product → Broadcast, Streamline
[data-product-price] → Themes that tag the price wrapper with this attribute
.price-container → Some Out of the Sandbox themes
.product-form__price → Themes that scope price inside the product form
{%- endcomment -%}
{%- assign default_price_selectors = '.product__price,.product-price,.product-single__price,.product__info-price,.price--product,[data-product-price],.price-container,.product-form__price' -%}
{%- if extra_price_selectors != '' -%}
{%- assign all_price_selectors = default_price_selectors | append: ',' | append: extra_price_selectors -%}
{%- else -%}
{%- assign all_price_selectors = default_price_selectors -%}
{%- endif -%}
{%- comment -%}
============================================================================
DYNAMIC PRICING DETECTION — runs at render time.
We only emit the snippet for bundles with Dynamic Pricing enabled.
Signal: `bundle_custom_prices_selection` metafield exists and is non-empty.
This metafield is only created when Dynamic Pricing is toggled ON in the
Simple Bundles app, regardless of whether custom prices are set or not.
============================================================================
{%- endcomment -%}
{%- assign has_dynamic_pricing = false -%}
{%- if product -%}
{%- for variant in product.variants -%}
{%- assign cps = variant.metafields.simple_bundles.bundle_custom_prices_selection.value -%}
{%- if cps != blank -%}
{%- assign has_dynamic_pricing = true -%}
{%- break -%}
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{% if has_dynamic_pricing %}
<script>
window.SBDynamicPricingData = {
productId: {{ product.id | json }},
shopCurrency: {{ shop.currency | json }},
cartCurrency: {{ cart.currency.iso_code | default: shop.currency | json }},
selectedVariantId: {{ product.selected_or_first_available_variant.id | json }},
defaultPriceSelectors: {{ all_price_selectors | json }},
// Pre-rendered fallback string from Liquid — guaranteed to be a valid price
// in the active page currency. Used if all JS calculations fail so the
// customer is never shown a blank price.
fallbackPriceDisplay: {{ product.selected_or_first_available_variant.price | money | json }},
variants: [
{% for variant in product.variants %}
{
id: {{ variant.id | json }},
price: {{ variant.price | json }},
// Dynamic-pricing source of truth — keyed by option group -> option value -> price
// (in major units, e.g. 50.0 = €50). Reflects custom prices if set, otherwise
// product prices. Always matches what Shopify will charge.
customPrices: {{ variant.metafields.simple_bundles.bundle_custom_prices_selection.value | default: '[]' | json }}
}{% unless forloop.last %},{% endunless %}
{% endfor %}
]
};
</script>
{% comment %}
Hide ALL matching default price elements. Activates only when our block has
successfully rendered a non-empty price (gated by data-sb-bundle-price-active).
{% endcomment %}
<style>
{%- assign selector_list = all_price_selectors | split: ',' -%}
{%- for sel in selector_list -%}
body[data-sb-bundle-price-active="true"] {{ sel | strip }}{% unless forloop.last %},{% endunless %}
{%- endfor -%}
{
display: none !important;
}
</style>
<script>
(function () {
if (window.__sbDynamicPDPInjectedPriceLoaded) return;
window.__sbDynamicPDPInjectedPriceLoaded = true;
const data = window.SBDynamicPricingData;
// ---------------------------------------------------------------------
// Selector resolution
// ---------------------------------------------------------------------
function getSelectorList() {
return (data.defaultPriceSelectors || '')
.split(',')
.map(s => s.trim())
.filter(Boolean);
}
function findFirstDefaultPriceElement() {
const selectors = getSelectorList();
for (const sel of selectors) {
try {
const el = document.querySelector(sel);
if (el) return el;
} catch (e) {}
}
return null;
}
// ---------------------------------------------------------------------
// Currency handling
// ---------------------------------------------------------------------
function getActiveCurrency() {
if (window.Shopify && window.Shopify.currency && window.Shopify.currency.active) {
return window.Shopify.currency.active;
}
return data.cartCurrency || data.shopCurrency || 'USD';
}
function getCurrencyRate() {
if (window.Shopify && window.Shopify.currency && window.Shopify.currency.rate) {
const r = Number(window.Shopify.currency.rate);
return isNaN(r) || r === 0 ? 1 : r;
}
return 1;
}
function isMarketsWithCustomPricing() {
const active = getActiveCurrency();
const shop = data.shopCurrency;
const rate = getCurrencyRate();
return active !== shop && rate === 1;
}
// ---------------------------------------------------------------------
// Form / variant / selection reading
// ---------------------------------------------------------------------
function parseJson(value) {
if (value == null || value === '') return [];
if (Array.isArray(value) || typeof value === 'object') return value;
try { return JSON.parse(value); } catch (e) { return []; }
}
function getForm() {
return document.querySelector('form[action*="/cart/add"]');
}
function getCurrentVariant() {
if (!data) return null;
const form = getForm();
const input = form ? form.querySelector('[name="id"]') : document.querySelector('[name="id"]');
const variantId = input && input.value ? Number(input.value) : Number(data.selectedVariantId);
return data.variants.find(v => Number(v.id) === variantId) || data.variants[0];
}
// Read currently checked IO radios -> { optionName: optionValue, ... }
// SB sometimes prefixes option names with a leading space — trim to match metafield keys.
function getSelectedOptions() {
const form = getForm();
const selected = {};
if (!form) return selected;
const fields = form.querySelectorAll(
'select[name^="properties"], input[name^="properties"]:checked, input[name^="properties"][type="hidden"], input[name^="properties"][type="text"]'
);
fields.forEach(field => {
const match = field.name.match(/properties\[(.*?)\]/);
if (!match || !field.value) return;
const key = match[1].trim();
if (key.startsWith('_')) return;
selected[key] = String(field.value).trim();
});
return selected;
}
// ---------------------------------------------------------------------
// Price calculation — single source of truth: bundle_custom_prices_selection
// ---------------------------------------------------------------------
function calculatePrice(variant, selected) {
const groups = parseJson(variant.customPrices);
if (!Array.isArray(groups) || groups.length === 0) return null;
let total = 0;
let matchedAny = false;
groups.forEach(group => {
if (!group || !group.option_name || !group.option_lookup) return;
const groupName = String(group.option_name).trim();
const chosenValue = selected[groupName];
if (!chosenValue) return;
const price = group.option_lookup[chosenValue];
if (price == null) return;
total += Number(price);
matchedAny = true;
});
return matchedAny ? total : null;
}
// ---------------------------------------------------------------------
// Formatting
// ---------------------------------------------------------------------
function formatMoney(amountMajor, currency) {
try {
const result = new Intl.NumberFormat(undefined, {
style: 'currency',
currency: currency
}).format(amountMajor);
if (result && result.trim()) return result;
} catch (e) {}
return amountMajor.toFixed(2) + ' ' + currency;
}
// ---------------------------------------------------------------------
// DOM injection
// ---------------------------------------------------------------------
function getInjectionTarget() {
const defaultPrice = findFirstDefaultPriceElement();
if (defaultPrice && defaultPrice.parentNode) {
return { type: 'after', node: defaultPrice };
}
const form = getForm();
if (form) {
return { type: 'prepend', node: form };
}
return null;
}
function injectPriceBlock() {
let block = document.querySelector('[data-sb-dynamic-pdp-price]');
if (block) return block;
const target = getInjectionTarget();
if (!target) return null;
block = document.createElement('div');
block.setAttribute('data-sb-dynamic-pdp-price', 'true');
block.className = 'sb-dynamic-pdp-price';
block.style.margin = '16px 0';
block.style.padding = '12px 14px';
block.style.border = '1px solid rgba(0,0,0,0.12)';
block.style.borderRadius = '8px';
block.style.fontSize = '16px';
block.style.lineHeight = '1.4';
block.innerHTML = `
<div style="font-size: 13px; opacity: 0.75; margin-bottom: 4px;">
Bundle price
</div>
<div data-sb-dynamic-pdp-price-value style="font-size: 22px; font-weight: 600;"></div>
<div data-sb-dynamic-pdp-price-note style="font-size: 12px; opacity: 0.65; margin-top: 6px; display: none;">
Estimated. Final price at checkout.
</div>
`;
if (target.type === 'after') {
target.node.parentNode.insertBefore(block, target.node.nextSibling);
} else if (target.type === 'prepend') {
target.node.insertBefore(block, target.node.firstChild);
}
return block;
}
// ---------------------------------------------------------------------
// Main refresh cycle
// ---------------------------------------------------------------------
function refreshPrice() {
let priceText = null;
// 1) Try the calculation from bundle_custom_prices_selection
try {
const variant = getCurrentVariant();
if (variant) {
const selected = getSelectedOptions();
const basePrice = calculatePrice(variant, selected);
if (basePrice != null && !isNaN(basePrice) && basePrice >= 0) {
const rate = getCurrencyRate();
const activeCurrency = getActiveCurrency();
priceText = formatMoney(basePrice * rate, activeCurrency);
}
}
} catch (e) {
// Fall through to fallback
}
// 2) Fallback: Liquid-rendered variant price — guaranteed valid string,
// already in the page's active currency. Used only if step 1 fails.
if (!priceText || !priceText.trim()) {
priceText = data.fallbackPriceDisplay || null;
}
// 3) If even the fallback is missing, do NOT hide the default price.
// Leave the page as-is so the customer always sees a price.
if (!priceText || !priceText.trim()) {
return;
}
const block = injectPriceBlock();
if (!block) return;
const value = block.querySelector('[data-sb-dynamic-pdp-price-value]');
if (!value) return;
value.textContent = priceText;
const note = block.querySelector('[data-sb-dynamic-pdp-price-note]');
if (note) {
note.style.display = isMarketsWithCustomPricing() ? 'block' : 'none';
}
// Only hide the default price once our block has a visible, non-empty price.
if (
value.textContent &&
value.textContent.trim() &&
document.body &&
document.body.getAttribute('data-sb-bundle-price-active') !== 'true'
) {
document.body.setAttribute('data-sb-bundle-price-active', 'true');
}
}
// ---------------------------------------------------------------------
// Event binding
// ---------------------------------------------------------------------
function bindEvents() {
document.addEventListener('change', function () { setTimeout(refreshPrice, 80); });
document.addEventListener('input', function () { setTimeout(refreshPrice, 80); });
document.addEventListener('variant:change', function () { setTimeout(refreshPrice, 150); });
document.addEventListener('product:variant-change', function () { setTimeout(refreshPrice, 150); });
document.addEventListener('shopify:section:load', function () { setTimeout(refreshPrice, 250); });
document.addEventListener('currency:change', function () { setTimeout(refreshPrice, 50); });
document.addEventListener('cart:currency:updated', function () { setTimeout(refreshPrice, 50); });
window.addEventListener('shopify:currency:changed', function () { setTimeout(refreshPrice, 50); });
}
document.addEventListener('DOMContentLoaded', function () {
bindEvents();
setTimeout(refreshPrice, 300);
});
setTimeout(refreshPrice, 800);
setTimeout(refreshPrice, 1500);
})();
</script>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment