Add an item to cart automatically if another item is in it.

seangerke
Excursionist
47 0 1

I am trying to have the customer do fewer steps buy adding this.

 

If the customer adds this one Event to the cart, I want the cart to automatically add this product. It has no variants, just one product.

 

I followed this: https://community.shopify.com/c/Shopify-Design/Add-Companion-Multiple-products-to-basket-when-specif...

 

And then found out I have an Ajax cart.... womp womp....

 

So I have tried making a form and adding an extra button for the product.

My product id for the item that needs to be added is 6619002634270.

 

I tried forcing the "Add to Cart" button to add it as well, all I could get is an event product with the cartridge products title. That was weird.

 

my site is:

 

orders.biomodex.com

 

The steps are:

 

Add Event: Patient Specific Rehearsal (this auto adds the product: Patient Specific Cartridge) to the cart.

 

I literally pulled my hair out trying to get this to work they way I want to. Any suggestions?

Replies 53 (53)

Tejas_Nadpara
Shopify Partner
1118 222 552

@seangerke 

 

This solution does require working with code and Liquid files, and if this is something you would not be comfortable with, I would advise you to reach out to one of Shopify Experts, or contact me by mail. As always, when making code changes to your theme, please remember to create a backup, in case you need to revert back to previous versions of the theme. 

 

Thank you,

Tejas

Shopify Expert | Skype: tejas.nadpara
- Like and Mark as an Accepted Solution if reply helpful
- Feel free to contact me on tejas.nadpara@gmail.com regarding any help
Jasoliya
Shopify Expert
4808 621 1217

Hi @seangerke 

In which condition you want to add extra product to cart?

Want custom changes? hire me.
3 months of Shopify for $1/month. Look here.
Email us Or WhatsApp, Try our Free app for product bundles and Codify Order Cancel or Order edit
Want to get Free review and advice for sale on store ?? just text me here
seangerke
Excursionist
47 0 1
Jasoliya,

I have one product that has a companion. Currently, it is a two step process. If you add this special event to your cart. You must add this 2nd product to your cart as well. This is the only time I would need this to work. One specific time. If you add event A you must add item B...

I am pretty deep into code but I still consider myself a novice. I usually edit code parameters, but not sure what everything needs or how it works.
Jasoliya
Shopify Expert
4808 621 1217

So you want like if product A in product then we need to add auto product B?

Want custom changes? hire me.
3 months of Shopify for $1/month. Look here.
Email us Or WhatsApp, Try our Free app for product bundles and Codify Order Cancel or Order edit
Want to get Free review and advice for sale on store ?? just text me here
seangerke
Excursionist
47 0 1
Yes, if product A is in cart auto add product B.

seangerke
Excursionist
47 0 1

I tried this:

 

{% for item in cart.items %}
{% if item.product.id == "29056231440487" %}
jQuery.post('/cart/update.js',
{
quantity:1,
id: 6619002634270

});

This is what I came up with but still not working. Am I adding the wrong IDs? First picture goes to the top, 2nd pic is reference to product I want added.product Aproduct A

product Bproduct B

Jasoliya
Shopify Expert
4808 621 1217

In this give instruction you can do this but need to change some code in Js to work with your condition.

Want custom changes? hire me.
3 months of Shopify for $1/month. Look here.
Email us Or WhatsApp, Try our Free app for product bundles and Codify Order Cancel or Order edit
Want to get Free review and advice for sale on store ?? just text me here
Jasoliya
Shopify Expert
4808 621 1217

But you need to add this Js code within  <script> tag

Want custom changes? hire me.
3 months of Shopify for $1/month. Look here.
Email us Or WhatsApp, Try our Free app for product bundles and Codify Order Cancel or Order edit
Want to get Free review and advice for sale on store ?? just text me here
ferdaus
Shopify Partner
13 0 1

Hi, when I print this

 

{{ product.metafields.custom.add_product_to_show }}

 

I got this  gid://shopify/Product/8019965837629

 

how can I show the above product title and description?

AEmedia
Shopify Partner
26 0 9

I think you would use: 

 

{% assign custom = product.metafields.custom.add_product_to_show %}

{{ custom.title }} 

{{ custom.description }}

 

Shopify Partner // Design + Development
ferdaus
Shopify Partner
13 0 1

Not working this way.

AEmedia
Shopify Partner
26 0 9

Slight change

 

{% assign custom = product.metafields.custom.add_product_to_show.value %}

{{ custom.title }} 

{{ custom.description }}

 

This is how I'm using something similar in a custom related items section.

Shopify Partner // Design + Development
seangerke
Excursionist
47 0 1

Thank you for reaching out. I have given up on this part and modified the "add-on" to just be automatically included on the back end.

Ninthony
Shopify Partner
2329 350 1023

Hmm, well part of the problem is that you're comparing the product id to a string I believe. I couldn't get that evaluation to be true until I took the product id out of the quotes. However, I still couldn't get it to execute my javascript. So instead of using liquid, I did everything in javascript and got this working:

 

  <script>
//get the cart
    let cart = $.getJSON('/cart.js');
// wait for the response
    cart.done(function(){
//when you have the response, get the JSON and set items to cart.items
    cart = cart.responseJSON;
    let items = cart.items;
// make a boolean to make sure that the item you want to add isnt already in the cart (to keep the JS from firing again on page reload)
    let item_in_cart_already = false;
//check the cart items and set boolean to true if the item is in the cart
      for(var i = 0; i < items.length; i++){
        if (items[i].product_id == 1999834054743){
        item_in_cart_already = true;
        }
      }
//then loop through cart items again and if the item isnt in the cart, and the corresponding product is found
//add it to the cart with the same quantity as the other product.
      if(!item_in_cart_already){
      for(var i = 0; i < items.length; i++){
        if (items[i].product_id == 1999834087511){
        let variant_quantity = items[i].quantity;
          Shopify.addItem(19754659905623, variant_quantity);
        }
      }
        setTimeout(function(){
        location.reload();
        },1000)
      }
    })    
  </script>

This is assuming you have the Shopify.addItem function in your store. You probably do already, but if you need it, here it is:

 

Shopify.addItem = function(variant_id, qty, properties, callback) {
  var qty = qty || 1;
  var params = {
    quantity: qty,
    id: variant_id
  }
  if(properties != false){
    params.properties = properties;
  }
  jQuery.ajax({
    type: "POST",
    url: "/cart/add.js",
    data: params,
    dataType: "json",
    success: function(line_item) {
      if ((typeof callback) === 'function') {
        callback(line_item);
      } else {
        Shopify.onItemAdded(line_item);
      }
    },
    error: function(XMLHttpRequest, textStatus) {
      Shopify.onError(XMLHttpRequest, textStatus);
    }
  });
};

That's what I came up with anyway. The only issue I saw is that if they update the quantity of their product on the cart page it will not update the quantity of the additional product.

If my solution helped you, please like it and accept it as the solution!
If you'd like to make any edits to your store, please send me a personal message and we can discuss what you'd like to accomplish 😄
jewellsolutions
Shopify Partner
2 0 1

Where are you adding this? To the cart.liquid file?

Ninthony
Shopify Partner
2329 350 1023

Yeah it's in cart.liquid, there was a mistake in the code I noticed later though. If any item was in the cart it was still reloading the page every second because I had the setTimeout set in the wrong place. Here's an updated version with variables for the product to compare against and the product to add's product id and variant_id -- to make it a little less confusing.

 

  <script>
    //get the cart
    let cart = $.getJSON('/cart.js');
    // wait for the response
    cart.done(function(){
      //when you have the response, get the JSON and set items to cart.items
      cart = cart.responseJSON;
      let items = cart.items;
      // make a boolean to make sure that the item you want to add isnt already in the cart (to keep the JS from firing again on page reload)
      let item_in_cart_already = false;
// product we are checking to see is in the cart let item_in_cart_prod_id = 1999834087511;
// the product we want to add's product id let item_to_add_prod_id = 1999834054743;
// the product we want to add's variant id let item_to_add_variant_id = 19754659905623;

//check the cart items and set boolean to true if the item is in the cart for(var i = 0; i < items.length; i++){ if (items[i].product_id == item_to_add_prod_id){ item_in_cart_already = true; } } //then loop through cart items again and if the item isnt in the cart, and the corresponding product is found //add it to the cart with the same quantity as the other product. if(!item_in_cart_already){ for(var i = 0; i < items.length; i++){ if (items[i].product_id == item_in_cart_prod_id){ let variant_quantity = items[i].quantity; Shopify.addItem(item_to_add_variant_id, variant_quantity); setTimeout(function(){ location.reload(); },1000) } } } }) </script>
If my solution helped you, please like it and accept it as the solution!
If you'd like to make any edits to your store, please send me a personal message and we can discuss what you'd like to accomplish 😄
BCR2020
Tourist
5 0 0

Hello! 

Thank you for the effort you put into this! 

I tried added your code to the Cart.liquid page and I did not succeed. I removed the variant piece for the added item (product B) because there is no variant and I'm not sure if that's why it isn't working. 

Please help! 

 

William

Ninthony
Shopify Partner
2329 350 1023

There is always a variant, even if you havent set any variants there's a default variant. You can echo out the variant id in product.liquid to figure out what it is with:

 

{{ product.first_available_variant.id }}
If my solution helped you, please like it and accept it as the solution!
If you'd like to make any edits to your store, please send me a personal message and we can discuss what you'd like to accomplish 😄
BCR2020
Tourist
5 0 0

I'm sorry, can you explain how I would find this default variant ID using the product.liquid page? 

BCR2020
Tourist
5 0 0

@Ninthony 

Great news. I was able to find my default Variant IDs (as you instructed). I correct your code in my cart.liquid file using the correct Product IDs, and Variant ID. 

After saving the file and testing, it did not auto-add Product B once I added Product A.

Any thoughts?

Ninthony
Shopify Partner
2329 350 1023

Couldn't tell you. I'd have to look at the code and debug it, I wrote this a while ago. You can message me your store URL and I can request access and take a look. Let me know what product you want to add automatically, and what item should be in the cart for it to happen.

If my solution helped you, please like it and accept it as the solution!
If you'd like to make any edits to your store, please send me a personal message and we can discuss what you'd like to accomplish 😄
julvir
Visitor
2 0 0

Ninthony, 

 

I have also similar problem, i try 10 apps... and i not manage make it working ( i want to keep AJAX cart ) 

 

your solution will work on AJAX cart ? if yes, how to contact you for you check my shop ? (it's my first post)

 

thank you 

seangerke
Excursionist
47 0 1

The app, Infinite Options works for this. I got locked into their free version from when they first came out, but not it costs $$ per month. But it worked great, takes a little understanding to get it to work the first time, but its just mouse clicks to get the feature to work.

julvir
Visitor
2 0 0

Thank you for your answer 

BCR2020
Tourist
5 0 0

Duplicate

Kamal81
Excursionist
21 1 3

Hi @Ninthony

Thanks for the solution and it's working fine in my store. That's great.

 

Just a small change I don't know how to do which is that I need one item A to be added to the cart when I add 3 or more of item B. Can you help me with that? 

 

Much appreciated.

Kam

seangerke
Excursionist
47 0 1

Kam,

Do a for loop through the cart items. Then add an if loop that looks for item B and its quantity == 3. Dont forget to stop the loop or it will run forever. Once your parameters are met not sure if its a {% break %} or stop to end the for loop at that time without keeping the search going like endfor

 

Hope this helps point you in rhe correct path! GL

Anthony726
Visitor
1 0 0

Hey there! I tried this code but my shop doesn't seem to have any of the Shopify functions (Shopify.addItem, Shopify.onError, etc.) Where are these functions normally found? I also get this error when it gets to the `url: "/cart/add.js"` part.

 

Thank you for this code by the way! Very well written.

 

seangerke
Excursionist
47 0 1

Its difficult to keep these codes up to date. As they add more features to the themes they are moving away from stagnant carts and are moving to these dynamic carts, which is great but completely different understanding of code. Most new these have some form of ajax cart which is like an auto refreshing cart and this code won't work for that unfortunately. I have since moved away from that,

 

But a similar coding would be: (i did not write all the {} () )

 

For items in cart.items

 If item is ....

  Add item ....

Endif endfor

bmahk
Visitor
3 0 0

You mentioned in a previous post that you figured out how to have the extra item added in the backend. How did you do this?

I'd love to find a solution to auto-add item A if item B is purchased, but it's not a requirement that the customer see this in their cart. What is most important is that when we are fulfilling the order, we're able to print a shipping label for both items. Manually adjusting each order to account for two boxes is time consuming. 

Let me know!

seangerke
Excursionist
47 0 1

That is why I moved away from the add A if B.

 

But if you are looking for code it starts with a for loop.

For item in cart.item

If item == A

Add B endif endfor

 

Thats basically what your code will look like. It should be added on the cart page. The specific code parameters will depend on your theme. Have fun and good luck.

 

 

 

Kamal81
Excursionist
21 1 3

Thanks @seangerke 

 

Actually, all I need is how to set the number of items needed in order to add item B.

 

The code is working fine for add one you get one item, which is good but I need to change it to buy 3 or more AND get one item.

 

Thanks for your reply.

 

Cheers,

seangerke
Excursionist
47 0 1
Click to expand...
Okay let me take a look tomorrow. Im replying on my phone and the code is too difficult to display properly on my system. 



I think you will need to use the function "assign" to set the qty to 3. {% assign B.quantity = 3 %} i dont know the qty parameter off the top of my head.
Kamal81
Excursionist
21 1 3

Hi @seangerke 

 

I used this code and it works fine, just I need to edit the part about the quantity:

 <script>
    //get the cart
    let cart = $.getJSON('/cart.js');
    // wait for the response
    cart.done(function(){
      //when you have the response, get the JSON and set items to cart.items
      cart = cart.responseJSON;
      let items = cart.items;
      // make a boolean to make sure that the item you want to add isnt already in the cart (to keep the JS from firing again on page reload)
      let item_in_cart_already = false;
// product we are checking to see is in the cart
      let item_in_cart_prod_id = 4167639433279;
// the product we want to add's product id
      let item_to_add_prod_id = 6591280775231;
// the product we want to add's variant id
      let item_to_add_variant_id = 39307370987583;

//check the cart items and set boolean to true if the item is in the cart
      for(var i = 0; i < items.length; i++){
        if (items[i].product_id == item_to_add_prod_id){
          item_in_cart_already = true;
        }
      }
      //then loop through cart items again and if the item isnt in the cart, and the corresponding product is found
      //add it to the cart with the same quantity as the other product.
      if(!item_in_cart_already){
        for(var i = 0; i < items.length; i++){
          if (items[i].product_id == item_in_cart_prod_id){
            let variant_quantity = items[i].quantity;
            Shopify.addItem(item_to_add_variant_id, variant_quantity);
            setTimeout(function(){
              location.reload();
            },1000)
          }
        }
      }
    })    
  </script>
AEmedia
Shopify Partner
26 0 9

I've tried this and I get an error on inspect:

 

Screen Shot 2021-07-06 at 4.53.23 PM.png

Shopify Partner // Design + Development
Ninthony
Shopify Partner
2329 350 1023

The code uses jQuery, which it appears your theme may not be using. You can include it in the head of the HTML before the opening body tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
If my solution helped you, please like it and accept it as the solution!
If you'd like to make any edits to your store, please send me a personal message and we can discuss what you'd like to accomplish 😄
AEmedia
Shopify Partner
26 0 9

Thanks @Ninthony I definitely should have thought of that!

But I'm still getting an error, a new one:

Shopify.addItem is not a function. (In 'Shopify.addItem(item_to_add_variant_id, variant_quantity)', 'Shopify.addItem' is undefined)
Shopify Partner // Design + Development
Ninthony
Shopify Partner
2329 350 1023

You can add this right under where you included jQuery, this is a bunch of little helper functions Shopify provides as an asset:

{{ 'api.jquery.js' | shopify_asset_url | script_tag }}

 

You can see them in action here:

https://mayert-douglas4935.myshopify.com/pages/api

Shopify.addItem is included in those functions.

If my solution helped you, please like it and accept it as the solution!
If you'd like to make any edits to your store, please send me a personal message and we can discuss what you'd like to accomplish 😄
AEmedia
Shopify Partner
26 0 9

Thank you @Ninthony that works!

Shopify Partner // Design + Development
Ninthony
Shopify Partner
2329 350 1023

Glad it works. You may want to change the setTimeout portion of it, that's likely to fail on slower devices. I did this before I understood callback functions more. You can provide a callback function as the third parameter for Shopify.addItem that will run after the item is added to the cart. 

//your addItem line
Shopify.addItem(item_to_add_variant_id, variant_quantity, reloadPage)

//somewhere outside the conditons, as long as the scope is within Shopify.addItem's scope.
function reloadPage(){
location.reload();
}
If my solution helped you, please like it and accept it as the solution!
If you'd like to make any edits to your store, please send me a personal message and we can discuss what you'd like to accomplish 😄
OrFreeSpirit
Visitor
3 0 0

Hello @Ninthony , thank you for this useful piece of code.
I'm also trying to use it, and when I click the add to cart button I get in the console the error 422: 
POST   https://zikger.co.il/cart/add    422


Do you know what it the problem?

Thanks!

Kamal81
Excursionist
21 1 3

Hi @Ninthony 

 

It's working fine, just I need to change it a bit to have this logic:

 buy 3 or more of item A AND get one item B.

 

Much appreciated,

Kamal

AndreasFandango
Shopify Partner
10 0 4

Where do I put this code? Get error when I try to include it in cart.json, but can I add it in cart.js?

seangerke
Excursionist
47 0 1

There are two types of Carts in Shopify. The auto-renewal carts (cart.json) and the stationary carts (cart.js) code will only work for a particular cart option. Just an FYI.

ferdaus
Shopify Partner
13 0 1

Hi, when I print this

{{ product.metafields.custom.add_product_to_show }}

I got this  gid://shopify/Product/8019965837629

 

how can I show the above product title and description?

BG417
Tourist
7 0 9

Sean,

I was looking for a way to automatically add a Mason Jar Deposit to Green Juices I sell at my retail store and believe I found a solution, although I've not yet fully tested it..

First, I created a product called "Mason Jar Deposit" and set the price to $1.25, unchecked inventory tracking and physical product, and made it active.

Then, I went to Discounts and created an automatic discount using the option 'Buy x, Get y'. Under 'Customer Buys' I set it to a minimum of (1) item for 'specific product' "Green Juice"; and under 'Customer Gets' chose 'specific product' "Mason Jar Deposit" at a 20% discount (since I actually want the deposit amount to be $1).

Not sure if this will work out the way I want, but thought it might be of help to your situation as well.

Cheers!

~ Bryce 

heenal
Visitor
3 0 0

Hi Bryce

Did that solution work for you? I am trying to do something similar for jar deposits at my package-free shop.

Does that solution work if a customer buys more than one products? For example, if a customer buys two green juices, does that solution give them two mason jar deposits?

Thanks for your help!

Heenal

seangerke
Excursionist
47 0 1

I believe it should. There are easy ways of testing this. Just create your own test-customer and after you make the edits. Add those items to your cart and see what happens. Good luck!

seangerke
Excursionist
47 0 1

@BG417 

Thank you for this. I did mine with coding and then eventually we removed that option because customers couldn't handle the products correctly.