d
Topic
Posts:
1
Last edited 7 months ago

If discount code is present, automatically add specific companion item to cart This post is outdated

Hi everyone. Web Developer here who is new to Shopify. I am trying to implement a JS function that does the following:

1. Check if specific discount code is present

2. If specific discount code is present, add specific companion item to cart

I am pretty much trying to create a work-around Shopify's discount limitations since they don't currently allow you to add a free gift with a promo code. Here is what I have so far but when I tried to test it, I got a message "Your cart does not meet the requirements for the MAGIC8 discount code."


{% assign linklist = linklists['free-hairband'] %}

{% if linklist.links.size > 0 %}

  <script>!window.jQuery && document.write('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"><\/script>')</script>
  
  <script>
  if (typeof Shopify === 'undefined') var Shopify = {};
	Shopify.cart = {{ cart | json }};
	Shopify.toAdd = {{ linklist.links.first.object.variants.first.id }};
	var pleaseAdd = false;
	var pleaseRemove = false;
	Shopify.idsInCart = [];
  
	for (var i = 0; i < Shopify.cart.items.length; i++) {
	  Shopify.idsInCart.push(Shopify.cart.items[i].id);
	  if (Shopify.cart.items[i].id !== Shopify.toAdd && Shopify.discount.code == "MAGIC8") {
	     pleaseAdd = true;
    } 
    else if (Shopify.discount.code != "MAGIC8") { // if discount code is not MAGIC8 remove item
			pleaseRemove = true;	
    }
	}

  if (pleaseAdd && (jQuery.inArray(Shopify.toAdd, Shopify.idsInCart) === -1)) {
    var params = {
      type: 'POST',
      url: '/cart/add.js',
      data: 'quantity=1&id=' + Shopify.toAdd,
      dataType: 'json',
      success: function(line_item) { 
        window.location.href = '/cart';
      }
    };
    jQuery.ajax(params);
  } else if (pleaseRemove) {
    var params = {
      type: 'POST',
      url: '/cart/update.js',
      data: 'updates[' + Shopify.toAdd + ']=0',
      dataType: 'json',
      success: function(line_item) { 
        window.location.href = '/cart';
      }
    };
    jQuery.ajax(params);
  }
  
  </script>

{% endif %}

 

i
Replies
Busfox Shopify Employee
Posts:
272
7 months ago

Hi Natalia,

The message you are seeing is returned when one of the following occurs.

  • The discount is expired
  • The discount id disabled
  • The discount has a use limit that has been reached
  • The discount does not meet the conditions of the discount

I would first try to determine which of these caused the error to appear, and make the necessary changes.

Cheers,

Andrew McCauley | Developer Experience @ Shopify | 1-888-746-7439