How to create an "Added to Cart" event for Shopify

read
Last updated at:

You will learn

Learn how to create a custom Added to Cart event for Shopify that tracks when a customer adds an item to their cart, which can be used to trigger an abandoned cart flow. Klaviyo’s built-in Shopify integration already tracks a Checkout Started event when a customer adds item(s) to their cart and then enters their email during the checkout process. 

  • The Checkout Started event is used to trigger the standard abandoned cart flow.
  • By creating an Added to Cart event, you can use it to trigger a second type of abandoned cart flow: one that triggers as soon as a customer adds an item to their cart.

Before you begin

Create the “Added to Cart” event

There are three steps to creating the Added to Cart event: 

  1. Choose where to place the code snippet
  2. Choose which code snippet to use
  3. Modify the code snippet (if necessary)

Klaviyo’s recommendations differ depending on the configuration of your Shopify store. 

Where should I paste my snippet?

If your store has custom liquid blocks, you should use one for your snippet 

  1. In Shopify, navigate to Online Store > Themes 
  2. Find your theme and click Customize
  3. At the top of the page, click the Home page dropdown
  4. Select Products > Default product to be brought to your default product page
  5. Click Add section in the left sidebar and then select Custom Liquid
  6. When you’ve chosen a snippet, and modified the snippet if necessary (see the next section), paste it in the box
  7. Click Save in the upper right
  8. In the left sidebar, your new Custom Liquid block for Added to Cart should automatically appear below the other sections on the page
    1. If your Added to Cart block needs to be moved, hover over the block and click the six dots to drag it below your other sections

If your store does not have custom liquid blocks, you should place your snippet in the theme.liquid file

  1. In Shopify, navigate to Online Store > Themes 
  2. Find your theme and click Customize
  3. Click the three dots at the top and select Edit code
  4. Open the theme.liquid file
  5. When you’ve decided what snippet to use, and modified the snippet if necessary (see the next section), paste it after all other code, before the closing </body> tagTheme.liquid file in Shopify showing text reading Snippet 1, 2, or 3 highlighted in yellow, followed by </body>
  6. Above the snippet, add the following opening tag: {% if product %}
    Theme.liquid file in Shopify showing if product tag followed by text reading Snippet 1, 2, or 3 highlighted in yellow, followed by </body>
  7. Directly after the snippet, add the following closing tag: {% endif %}
  8. Your file should look like this:
    Theme.liquid file in Shopify showing if product and endif tags surrounding text reading Snippet 1, 2, or 3 highlighted in yellow, followed by </body>
  9. Click Save

Which snippet should I use?

Consult the questions below to choose which snippet to use. Once you have chosen your snippet, learn how to modify each (if necessary) using the sections below. 

  1. Does your store redirect customers to another page, such as the checkout or cart page, after they add an item to their cart? If the answer is no, you should use Snippet 1. If the answer is yes, go to step 2.
  2. Does your store use a button ID to define the Added to Cart button? If the answer is yes, ‌use Snippet 2. If the answer is no, go to step 3. If you are unsure of the answer:
    1. Open up one of your site’s product pages 
    2. Right-click the "Add to Cart" button, and select Inspect
    3. The console will open, showing the source code of your "Add to Cart" button in the console’s Elements tab
    4. In the Elements tab, your code may look something like this:
      Product page with coffee bag on left and console open to Elements tab, with inspect element pop up above Add to Cart and button code highlighted in console
    5. Notice that this "Add to Cart" button does not have a button ID (which would include something like id = “button_ID_name); instead, it is referenced by a class notation (class= “btn product-form_cart-submit btn–secondary-accent)
  3. Does your store use class notation to define the Added to Cart button? If the answer is yes, ‌use Snippet 3.  

Snippet 1: For buttons without redirects

If it does not redirect your customers to another page, such as the checkout or cart page, after adding an item to their cart, use the following snippet:

<script type="text/javascript">
var _learnq = _learnq || [];
function addedToCart() {
  fetch(`${window.location.origin}/cart.js`)
  .then(res => res.clone().json().then(data => {
    var cart = {
      total_price: data.total_price/100,
      $value: data.total_price/100,
      total_discount: data.total_discount,
      original_total_price: data.original_total_price/100,
      items: data.items
    }
    if (item !== 'undefined') {
      cart = Object.assign(cart, item)
    }
    _learnq.push(['track', 'Added to Cart', cart])
  }))
} 
(function (ns, fetch) {
  ns.fetch = function() {
    const response = fetch.apply(this, arguments);
    response.then(res => {
      if (`${window.location.origin}/cart/add.js`
      	.includes(res.url)) {
        	addedToCart()
      }
    });
    return response
  }
}(window, window.fetch))
$(document).ajaxComplete(function(event, request, settings){
  if(settings.url == "/cart/add.js"){
      addedToCart()
  }
})
</script>

The content of this snippet does not need to be modified. Make sure to review the “Where should I paste my snippet?” section above, because you may need additional tags depending on where the snippet is placed.

Snippet 2: For buttons with redirects defined by a button ID

If your customers are redirected to the checkout page after adding an item to their cart, and your Add to Cart button is defined by a button ID, use the following snippet:

<script type="text/javascript">
var _learnq = _learnq || [];
	document.getElementById("AddToCart").addEventListener('click',function (){
 		_learnq.push(['track', 'Added to Cart', item]);
	});
</script>

This snippet will likely need to be modified, because the Add to Cart variable in the snippet needs to match the button ID used on your site.

The Add to Cart variable, whose default name is AddToCart, is highlighted within the snippet below:
Klaviyo's Added to Cart snippet with Add to Cart button ID highlighted in yellow

Checking the ID of the button requires the same steps as checking for the presence of a button ID on your site: 

  1. Open up one of your site’s product pages.
  2. Right-click your "Add to Cart" button and select Inspect.
  3. The console will open, showing the source code of your "Add to Cart" button. The following image shows the ID of the "Add to Cart" button highlighted in the console.
    Add to cart button code in console with ID equals addToCart-product-template
    The ID of the button on the page shown here (addToCart-product-template) is different from the variable in the default snippet (AddToCart). 
  4. If they don’t match, modify the snippet to match the ID of your button. Our example’s modified snippet looks like this:
    Klaviyo's add to cart snippet defined by button ID with add to cart variable modified to be addToCart-product-template

The content of your snippet should be all set, but make sure to review the “Where should I paste my snippet?” section above, because it may need additional tags depending on where the snippet is placed.

Snippet 3: For buttons with redirects defined by class notation

If your customers are redirected to the checkout page after adding an item to their cart, and your Add to Cart button is defined by class notation, you should use the following snippet:

<script type="text/javascript">
var _learnq = _learnq || [];
  var classname = document.getElementsByClassName("add-to-cart");
var addToCart = function() {
_learnq.push(['track', 'Added to Cart', item]);
}; for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', addToCart, false);
}
</script>

This snippet will likely need to be modified, because the Add to Cart variable in the snippet needs to match the class used on your site.

  1. Open up one of your site’s product pages.
  2. Right-click your "Add to Cart" button and select Inspect.
  3. The console will open, showing the source code of your "Add to Cart" button. The following image shows the class of the "Add to Cart" button highlighted in the console.
    Add to cart button code in console with class equals btn product-form_cart-submit btn--secondary-accent highlighted in yellow
  4. Compare your button code in between the quotations, highlighted in the above example, with the contents in between the parentheses after getElementsByClassName in the code snippet above. For example, the class listed in the screenshot is btn product-form_cart-submit btn--secondary-accent and the variable listed in the snippet is add-to-cart.
  5. If they don’t match, modify the snippet to match the class of your button. Our example’s modified snippet looks like this:
    Klaviyo's alternate Added to Cart snippet with classname value btn product-form_cart-submit btn--secondary-accent

The content of your snippet should be all set, but make sure to review the “Where should I place my snippet?” section above, because it may need additional tags depending on where the snippet is placed.

If you are encountering problems with your Added to Cart snippet after trying these different options, it could be due to an issue with identifying the Added to Cart button. In this case, please contact Klaviyo support.

Outcome 

You have now created a Shopify Added to Cart event, which you can monitor in Klaviyo and use to trigger an abandoned Added to Cart flow. 

Next step: Enable the abandoned “Added to Cart” flow

The standard abandoned cart reminder flow is triggered by the Checkout Started event. The Added to Cart abandoned cart flow targets more casual potential shoppers who have yet to start checkout.

To enable this flow, we recommend using the pre-built flow available in Klaviyo's flow library:

  1. Navigate to Klaviyo’s flow library
  2. Click into the "Prevent lost sales" goal section
  3. Select the Abandoned Cart Reminder, Added to Cart Trigger flow
    Card in Klaviyo flows library showing Added to Cart triggered Abandoned Cart reminder flow for Shopify
  4. If you created the Added to Cart event, this flow will be ready to go with all the recommended filters and dynamic email content ready to power personalized cart followup emails

Additional resources

x
Was this article helpful?
812 out of 1527 found this helpful