Match number of auto add-on products with number of products added in cart

New Member
2 0 0

Hello

I am currently using the code below to addon a product automicatly when something is added to the cart.
For example if a customer purchases a painting then a frame for the painting is automatically added to the cart.

Here is the code for the liquid:

https://github.com/carolineschnapp/add-product-to-cart-automatically

{% assign product = all_products['put-your-product-handle-here'] %}

{% unless cart.item_count == 0 or product.empty? or product.variants.first.available == false %}

  {% assign variant_id = product.variants.first.id %}

  <script>
  (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);
  </script>

{% endunless %}

Currently only 1 add on is added even if the customer purchases two regular products. I wanted the addon to match the total amount of other items in the cart. So if a 5 paintings are added to the cart then 5 frames should also be added automatically.

I tried changing the values in the liquid code above but could not get it to work. 

0 Likes
Highlighted
Shopify Staff
Shopify Staff
81 0 11

Hey! I'll move this thread to Shopify Design, I think you'll get more help there

0 Likes