Reputation: 1
I'm trying to make a bundle in shopify using only liquid code. Like if I have a bag and it's added to cart, a jacket is added with it automatically. I'm a rookie in Shopify so if someone could give me some leads as in where should I start.
I tried adding an event listener for clicking on the ATC button but I can't extract the product id on the product page. I'm desperate for some leads on this 😭Thank you! And how can I check that what's happening once the Add to cart button is clicked?
Upvotes: 0
Views: 811
Reputation: 120
If I understood correctly, when the customer clicks the ATC button on a product, you want to add an extra product to the cart besides the one the customer is actually adding.
Usually I prefer the AJAX API for this approach. Take a look at this code:
<script>
const addToCartBtn = document.querySelector("#addToCart")
addToCartBtn.addEventListener('click', async function() {
const extraItem = {
items: [
{
id: 44714049634597, // ID of the variant you want to add to the cart
quantity: 1,
},
],
};
const response = await fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(extraItem),
});
if (!response.ok) console.log('Upss something went wrong');
console.log(await respons.json());
});
</script>
Basically what this code does is that when the user clicks the ATC button, we send a request to the cart/add API with the extra Item as the body of the request. Learn how to get the variant ID here.
If you want to make this function more dynamic and reusable, try using metafields. Go to the admin dashboard and create a product metafield to help you reference the desired product. So now the request body should look like this:
const extraItem = {
items: [
{
id: {{ product.metafields.custom.bundle_product.id }}
quantity: 1,
},
],
};
Since we are using liquid now, make sure to place this code inside a script tag in the main-product.liquid file (also named product.liquid in some themes).
Hope this helps!
Upvotes: 0