I would like to have a custom button in Shopify that would add certain item to card on click based on a fixed product ID.
I did try to add this code to custom HTML on a custom page in the page editor:
page editor
<button id="custom-add-to-cart" data-product-id="11564478366041">Add to Cart</button>
And this javascript code to a new asset file named custom.js:
document.getElementById('custom-add-to-cart').addEventListener('click', function() {
var productId = this.getAttribute('data-product-id');
addToCart(productId, 1); // 1 indicates the quantity
function addToCart(productId, quantity) {
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
id: productId,
quantity: quantity
})
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Product added to cart:', data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
}
});
And this to the theme.liquid:
<script src="{{ 'custom.js' | asset_url }}"></script>
New contributor
Filip Dolanský is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.