Reputation: 103
I've started a books series called Ribbon & Robin and have set up a Shopify store to sell Books and Merchandise. Books and Merchandise are both set up as different 'collections' inside the Shopify story. Merchandise products have multiple variants (size, colour). Books products have no variants.
here for reference - https://ribbonandrobin.com/
What I am trying to do is add an ADD TO CART button on the homepage that automatically adds all products from whatever products are in the Books collection to cart. And ignores products in the Merchandise collection.
Is there an easy way to do this? Can anyone suggest a snippet of code that will work??
I have already tried code suggested here with no luck. Shopify support mentioned it would be possible but said I should figure out how on my own through trial and error.
Upvotes: 0
Views: 2610
Reputation: 12943
It's not too hard to do this.
You need to loop all of your products from a specific collection ( in this case the books ) and output their variants as hidden inputs.
You wrap all of them with a form element and you add a submit button. Standard thing.
The only important thing is to add square brackets for the hidden input name, so that you can add all of them and not only the last one.
So in code it will look like this:
<form id="add-item-form" action="/cart/add" method="post">
{% for product in collections['book'].products %}
<input type="hidden" name="id[]" value="{{ product.variants[0].id }}">
{% endfor %}
<input type="submit" id="add-to-cart" name="add" value="Add All Products to Cart" />
</form>
Upvotes: 2