Add a product to the cart automatically

Add a product to the cart automatically

create the product to upsell.

Create snippet

Create snippet named cart-add-on.liquid and add the following code. Replace ['put-your-product-handle-here'] with the handle of the product created in the previous step.  
{% comment %}
  Replace the text below with the handle of your add-on product.
{% endcomment %}

{% 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 %}
 
 

Optional

Hide or style upsell differently (Optional)

Open cart.liquid

Find the first <tr> directly after {% for i in cart.items %} and replace the <tr> with the following code:  
<tr {% if i.product.handle contains 'add-on-test-product' %}class="product-add-on"{% endif %}>
 

custom.scss

Open custom.scss and add the following code.  
tr.product-add-on {
    opacity: .5;
}

Leave a comment