Last active
February 10, 2025 17:25
-
-
Save tkirrane/9472722 to your computer and use it in GitHub Desktop.
Add a companion product to cart page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% comment %} | |
To add a companion product to the cart automatically if a primary product is in cart: | |
1. Create a new link list under your Navigation tab. | |
2. In that link list, make the first link point to companion product. | |
3. Copy your link list handle where indicated at line 8: | |
{% endcomment %} | |
{% assign linklist = linklists['put-your-link-list-handle-here'] %} | |
{% comment %} | |
You're done. Include this code in cart.liquid at the top or bottom. | |
{% endcomment %} | |
{% if linklist.links.size > 0 %} | |
<script>!window.jQuery && document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"><\/script>')</script> | |
<script> | |
if (typeof Shopify === 'undefined') var Shopify = {}; | |
Shopify.cart = {{ cart | json }}; | |
Shopify.toAdd = {{ linklist.links.first.object.variants.first.id }}; | |
var pleaseAdd = false; | |
Shopify.idsInCart = []; | |
for (var i=0; i<Shopify.cart.items.length; i++) { | |
Shopify.idsInCart.push(Shopify.cart.items[i].id); | |
if (Shopify.cart.items[i].id !== Shopify.toAdd) { | |
pleaseAdd = true; | |
} | |
} | |
if (pleaseAdd && (jQuery.inArray(Shopify.toAdd, Shopify.idsInCart) === -1)) { | |
var params = { | |
type: 'POST', | |
url: '/cart/add.js', | |
data: 'quantity=1&id=' + Shopify.toAdd, | |
dataType: 'json', | |
success: function(line_item) { | |
window.location.href = '/cart'; | |
} | |
}; | |
jQuery.ajax(params); | |
} | |
</script> | |
{% endif %} |
Nice solution. But what if you add multiple quantities of the parent product? Your solution is only adding 1 instance of the companion product no matter how many quantities of parent product are in cart.
Thank you for this!! Trying to find a different solution to add a gift to the shopping cart when they buy a specific product (without having to pay $25 a month for the app) and so glad I found this! So far, it's the closest I've been able to get.
I was able to implement it, and even edit it with @cpres addition to at least control the minimum price, but running into a big problem. Any idea how to remove the option for someone to add to the quantity of the gift?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this wasn't working for me on Safari for iPhone. Works now that I made this link:
http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
https instead of http