Shopify: Automatically add item to cart when another item is added


My client is using Shopify plus, So I don’t know if this will only work on Shopify plus or just regular. But any who this is what we did. We combined the Shopify Automatic Discounts and some custom code to make it happen. We wanted to add a free CD with every purchase of the book. You need to have both products for sale in your store for this to work. And you will only get the CD Free if you order a Book. In the below code if the title of any item in your cart includes book it will automatically add the item that you please to the users Cart.

In cart.liquid

{% if cart.item_count > 0 %}
 {% for item in cart.items %}
 {% if item.product.title contains'Book' %}
 {% comment %}
   Replace the text below with the handle of your add-on product.
 {% endcomment %}
 {% assign product = all_products['the-slug-of-the-product'] %}
 {% unless cart.item_count == 0 or product.empty? or product.variants.first.available == false %}
 {% assign variant_id = product.variants.first.id %}
   (function($) {     var cartItems = {{ cart.items | json }},         qtyInTheCart = 0,         cartUpdates = {};     for (var i=0; i<cartItems.length; i++) {       if ( cartItems[i].id === {{ variant_id }} ) {         qtyInTheCart = cartItems[i].quantity;         break;       }     }     if ( ( cartItems.length === 1 ) && ( qtyInTheCart > 0 ) ) {       cartUpdates = { {{ variant_id }}: 0 }     }     else if ( ( cartItems.length >= 1 ) && ( qtyInTheCart !== 1 ) ) {       cartUpdates = { {{ variant_id }}: 1 }     }     else {       return;     }     var params = {       type: 'POST',       url: '/cart/update.js',       data: { updates: cartUpdates },       dataType: 'json',       success: function(stuff) {          window.location.href = '/cart';       }     };     $.ajax(params);   })(jQuery);   
 {% endunless %}
 {% endif %}
 {% endfor %}
 {% endif %}

This above code ads the item to the users cart if they have anything in there cart that has anything that is titled book.

Then in Shopify Discounts we select if “Buy X get Y”:

Then we can select if they buy anything in the Book Category:

Then we select what the discount that the customer gets, In this case they get the CD Free:

We were using an app and it wasn’t working quite properly, so this made it all good in the hood.