kelly-v
12/3/2016 - 9:09 PM

(Shopify) Snippet to auto add product to cart based on Bold Product Options selection (one-time fee)

(Shopify) Snippet to auto add product to cart based on Bold Product Options selection (one-time fee)

{% assign totes_addon = all_products['custom-tote-new-order-fee'] %}
{% assign pouches_addon = all_products['custom-pouches-new-order-fee'] %}
{% assign cards_addon = all_products['custom-cards-new-order-fee'] %}

{% unless cart.item_count == 0 %}

  {% assign totes_id = totes_addon.variants.first.id %}
  {% assign pouches_id = pouches_addon.variants.first.id %}
  {% assign cards_id = cards_addon.variants.first.id %}

  <script>
  (function($) {
    var cartItems = {{ cart.items | json }},
        qtyInTheCart = 0,
        new_totes = 0,
        new_pouches = 0,
        new_cards = 0,
        customOrder = false,
        sumCustom = new_totes + new_pouches + new_cards,
        cartUpdates = {};
    for (var i=0; i<cartItems.length; i++) {
      if ( cartItems[i].id === {{ totes_id }} || cartItems[i].id === {{ pouches_id }} || cartItems[i].id === {{ cards_id }} ) {
          qtyInTheCart = qtyInTheCart + cartItems[i].quantity;
      } else {
          if(cartItems[i]['properties']){
            if(~cartItems[i]['properties']['Is this a new custom order?'].indexOf("Yes")){
              var customOrder = true;
              if(~cartItems[i].product_title.indexOf("Pouch")){
                new_pouches = new_pouches + 1;
              }
              if(~cartItems[i].product_title.indexOf("Tote")){
                new_totes = new_totes + 1;
              }
              if(~cartItems[i].product_title.indexOf("Card")){
                new_cards = new_cards + 1;
              }
              sumCustom = new_totes + new_pouches + new_cards;
            }
          }
      }
    }
    if ( sumCustom !== qtyInTheCart ) {
      cartUpdates = { {{ totes_id }}: new_totes, {{ pouches_id }}: new_pouches, {{ cards_id }}: new_cards }
    }
    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 %}