Automatically add hidden line item properties

noah_haub
Shopify Partner
25 2 5

Hey,

 

I'm currently building a tracking software for Shopify stores.

I want to provide a JS script that will track visitors' actions on the store. This script will be added to their theme.liquid page.

 

I track the orders by adding a hidden line item property to one of the items in the cart. That property is all I need to basically know how the customer got to the point of purchasing the product.

 

The issue I am facing is that I can't add the line item property when someone lands on the page, because at that point there are no line items yet. So when a customer lands on the page and immediately proceeds to checkout after adding to cart, without going to the carts page (and therefore reloading the page) the hidden property does not get added.

 

So my question is:

How do I automatically add hidden line item properties as soon as items get added to the cart? Is something like that possible?

I have checked out Webhooks, so I believe that that would be an option but I'm curious if I can achieve this without webhooks as well.

I worked with cart attributes before, which worked great. But I realized that they get ignored when a customer clicks on the dynamic checkout button. So I figured line item properties would make more sense.

 

I hope I didn't phrase my question too confusing and that you understand what I am having trouble with.

I would really appreciate any kind of help on this.

Looking forward to hearing from you.

Kind regards,

Noah

Reply 1 (1)

EcomGraduates
Shopify Partner
588 48 79

To automatically add hidden line item properties as soon as items get added to the cart, you can use Shopify's Cart API. You can use the "addItem" method to add an item to the cart and set the hidden line item property at the same time. Here's an example:

 

var item = {
  quantity: 1,
  id: {{ product.id }},
  properties: {
    'my_property_name': 'my_property_value'
  }
};

Shopify.addItem(item, function(cart) {
  // Success callback
}, function(XMLHttpRequest, textStatus) {
  // Error callback
});