Skip to content

Instantly share code, notes, and snippets.

@shafiimam
Last active August 27, 2023 05:04
Show Gist options
  • Save shafiimam/a9529e4bc4b406b13f46d8e79412d2aa to your computer and use it in GitHub Desktop.
Save shafiimam/a9529e4bc4b406b13f46d8e79412d2aa to your computer and use it in GitHub Desktop.
Shopify selling plan product add to cart
<div class="productGrid__formItem">
{%- liquid
assign current_variant = product.selected_or_first_available_variant | default: product.variants.first
assign current_selling_plan_allocation = current_variant.selected_selling_plan_allocation
if current_selling_plan_allocation == nil and current_variant.requires_selling_plan
assign current_selling_plan_allocation = current_variant.selling_plan_allocations | first
endif
assign offer = current_selling_plan_allocation | default: current_variant
assign offerPrice = offer.price
assign discount = offer.price | times: 0.1
assign discountedPrice = offerPrice | minus: discount
-%}
<div>
{{ current_selling_plan_allocation.price }}
<div class="dn-selling-plan-container">
{% for group in product.selling_plan_groups %}
<fieldset>
<legend>Select a subscription below</legend>
<select class="dn-selling-plans" data-variant-id="{{ current_variant.id }}">
{% for selling_plan in group.selling_plans %}
<option value="{{ selling_plan.id }}" {% if forloop.first %}selected{%endif%}>Delivery {{ selling_plan.name }}</option>
{% endfor %}
</select>
</fieldset>
<button class="dn-subscribe-btn">Subscribe - {{ discountedPrice | money }}</button>
{% endfor %}
</div>
</div>
</div>
<script>
let sellingPlanContainer = document.querySelector('.dn-selling-plan-container')
let submitBtn = document.getElementsByClassName('dn-subscribe-btn');
$('.dn-subscribe-btn').on('click',function(){
console.log('adding selling plan')
const sellingPlanId = $(this).prev().closest("fieldset").find('select').val();
const variantId = $(this).prev().closest("fieldset").find('select').attr('data-variant-id')
let formData = {
'items': [{
'id': variantId,
'quantity': 1,
'selling_plan': sellingPlanId,
}]
}
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => {
return response.json();
})
.then(data=> window.location.href="/cart")
.catch((error) => {
console.error('Error:', error);
});
})
</script>
@ramdhanishivam
Copy link

🎉

@raymondarevalo
Copy link

Did you ever find a method that didn't require a page refresh and instead opened the cart once added to cart?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment