Skip to content

Instantly share code, notes, and snippets.

@BrunoBoehm
Forked from lambtron/shopify.md
Created September 7, 2017 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrunoBoehm/cd625cec2479ddf5be18fadd91fa5e50 to your computer and use it in GitHub Desktop.
Save BrunoBoehm/cd625cec2479ddf5be18fadd91fa5e50 to your computer and use it in GitHub Desktop.
segment event tracking for shopify
title sidebar
Segment Event Tracking for Shopify
Shopify

Segment makes it simple for Shopify merchants to integrate analytics, email marketing, advertising and optimization tools. Rather than installing all your tools individually, you just install Segment once. We collect your data, translate it, and route it to any tool you want to use with the flick of a switch. Using Segment as the single platform to manage and install your third-party services will save you time and money.

The guide below explains how to install Segment in your Shopify store. All you need to get up and running is copy and paste a few snippets of code into your theme editor. (You don't have to edit the code or be versed in JavaScript.) The following guide will show you how, step by step.


Step 1: Segment Account

Start by creating a Segment account. We recommend creating an organization so you can invite teammates to your account in the future.

Once your account is created, add a new project for your store.

Step 2: Install Segment Code

Once your Segment account is ready to go you'll need to install a few lines of javascript into your Shopify theme templates.

Everything you need can be found in your Shopify Admin under Themes > Customize Theme > Edit HTML/CSS. Each section below includes a reference to one of the folders and liquid templates that can be found on the left side of this page.

If you want to track all events as noninteraction to GA make sure to add an event prop for that.

2a: Add Your Snippet to All Pages

  • Folder: Layouts
  • File: theme.liquid

Add the following snippet to the line above the </head> tag on your main theme.liquid template file. Doing this will load the Segment javascript library (Analytics.js) on every page of your Shopify store.

Make sure you replace YOUR_WRITE_KEY with the write key found in your setup page (click on the wrench icon from inside your Segment project).

<script type="text/javascript">
  window.analytics=window.analytics||[],window.analytics.methods=["identify","group","track","page","pageview","alias","ready","on","once","off","trackLink","trackForm","trackClick","trackSubmit"],window.analytics.factory=function(t){return function(){var a=Array.prototype.slice.call(arguments);return a.unshift(t),window.analytics.push(a),window.analytics}};for(var i=0;i<window.analytics.methods.length;i++){var key=window.analytics.methods[i];window.analytics[key]=window.analytics.factory(key)}window.analytics.load=function(t){if(!document.getElementById("analytics-js")){var a=document.createElement("script");a.type="text/javascript",a.id="analytics-js",a.async=!0,a.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.io/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n)}},window.analytics.SNIPPET_VERSION="2.0.9",

  window.analytics.load("YOUR_WRITE_KEY");

  // identify the customer if they have an account
  {% if {{ customer.id }} %}
  window.analytics.identify({{customer.id}}, {
    name: "{{ customer.name }}",
    firstName: "{{ customer.first_name }}",
    lastName: "{{ customer.last_name }}",
    email: "{{ customer.email }}",
    phone: "{{ customer.default_address.phone }}",
    address: {  // uses the default address
      street: "{{ customer.default_address.street }}",
      city: "{{ customer.default_address.city }}",
      state: "{{ customer.default_address.province }}",
      stateCode: "{{ billing_address.province_code }}",
      postalCode: "{{ customer.default_address.zip }}",
      country: "{{ customer.default_address.country }}",
      countryCode: "{{ customer.default_address.country_code }}"
    },
    totalSpent: "{{ customer.total_spent }}",
    allOrdersCount: {{ customer.orders_count }},
    allOrderIds: [{% for order in customer.orders %}{{ order.id }},{% endfor %}],
    tags: ["{{ customer.tags | join: '", "' }}"]
  });
  {% endif %}
  window.analytics.page();
</script>

2b: Category (Collection) Pages

  • Folder: Templates
  • File: collection.liquid

This tracks your proudct category pages (referred to as collections in Shopify).

<script type="text/javascript">
  analytics.track('Viewed Product Category', {
    category: "{{ collection.title }}",
    categoryUrl: "{{ collection.url }}",
    categoryProductCount: {{ collection.all_products_count }},
    {% if collection.current_type %} filteredType: "{{ collection.current_type }}"{% endif %},
    {% if collection.current_vendor %} filteredVendor: "{{ collection.current_vendor }}"{% endif %},
    defaultSortBy: "{{ collection.default_sort_by }}",
    referrerUrl: document.referrer,
    referrerPath: new URL(document.referrer).pathname,
    urlHref: window.location.href,
    urlPath: window.location.pathname,
    urlHash: window.location.hash
  });
</script>

2c: Product Pages

  • Folder: Templates
  • File: product.liquid

This script tracks when visitors view producta and an Added Product event when they add products to their cart.

<script type="text/javascript">
  analytics.track('Viewed Product', {
    id: "{{ product.id }}",
    name: "{{ product.title }}",
    type: "{{ product.type }}",
    url: "{{ product.url }}",
    price: {{ product.price }},
    priceMin: {{ product.price_min }},
    priceMax: {{ product.price_max }},
    priceVaries: {{ product.price_varies }},
    variantsCount: {{ product.variants.size }},
    firstAvailVariant: "{{ product.first_available_variant.title }}",
    variantId: {{ product.selected_variant.id }},
    variantAvailable: {{ variant.available }},
    variantCompareAtPrice: {{ variant.compare_at_price }},,
    variantQuantity: {{ variant.inventory_quantity }},
    variantPrice: {{ variant.price }},
    variantSelected: {{ variant.selected }},
    sku: "{{ variant.sku }}",
    variantTitle: "{{ variant.title }}",
    variantUrl: "{{ variant.url }}",
    variantWeight: "{{ variant.weight }}",
    vendor: "{{ product.vendor }}",
    collections: [{% for collection in product.collections %}"{{ collection.title }}",{% endfor %}],
    available: {{ product.available }},
    options: ["{{ product.options | join: '", "' }}"],
    optionsCount: {{ product.options.size }},
    tag: ["{{ product.tags | join: '", "' }}"]
  });
  
  // track Product Added event
  
  var form = document.getElementById('add-to-cart');
  // or your form's ID

  analytics.trackForm(form, 'Added Product', {
    id: {{ item.id }},
    name: "{{ item.title }}",
    price: {{ item.price }},
    quantity: {{ item.quantity }},
    value: {{ item.quantity }}*{{ item.price }}
  });
</script>

2d: Cart Page

  • Folder: Templates
  • File: cart.liquid

This script tracks the cart page and events for Removed Product and Updated Product when a product is removed from the cart or the quantity is updated.

<script type="text/javascript">
  analytics.track('Viewed Cart', {
    itemCount: {{ cart.item_count }},
    totalPrice: {{ cart.total_price }},
    totalWeight: {{ cart.total_weight }}
  });

</script>

2f: Thank You Page

This tracks the Completed Order event that records all your transaction data to Segment. To add a script to your thank you page, you'll leave the theme editor and go to your checkout settings page: http://myshopify.com/admin/settings/checkout

In the "Additional content scripts" field, shown above, paste the following code:

  <script type="text/javascript">
  var discounts = {{ order.discounts | json }}
  var totalDiscount = 0;
  
  for (var i = 0; i< discounts.length; i++ ) {
    totalDiscount += discounts[i].savings;
  }
  
  window.analytics.track('Completed Order', {
    orderId: {{ order_number }},
    total: {{ total_price | money_without_currency }},
    revenue: {{subtotal_price | money_without_currency }},
    shipping: {{shipping_price | money_without_currency }},
    tax: {{tax_price | money_without_currency }},
    discount: totalDiscount,
    products: [
    {% for line_item in line_items %}
    {
      id: "{{ line_item.id }}",
      sku: "{{ line_item.sku }}",
      name: "{{ line_item.title }}",
      price: "{{ line_item.price }}",
      quantity: {{ line_item.quantity }}
    },
    {% endfor %} ]
    });
  </script>

2x: Track the Index Page

  • Folder: Templates
  • File: index.liquid
<script type="text/javascript">
  analytics.track('Viewed Index');
</script>

2x: Track Other Pages

  • Folder: Templates
  • File: page.liquid

This will also track the contact page automatically (page.contact.liquid).

<script type="text/javascript">
  analytics.track('Viewed Page', {
    title: "{{ page.title }}",
    url: "{{ page.url }}",
    author: "{{ page.author }}",
    handle: "{{ page.handle }}",
    id: {{ page.id }}
  });
</script>

2x: Track Blog Pages

  • Folder: Templates
  • File: blog.liquid

This script tracks your blog home page.

  <script type="text/javascript">
  window.analytics.track('Viewed Blog', {
    pageType: 'Front Page',
    pageTitle: document.title,
    blogArticleCount: {{ blog.articles_count }},
    blogTitle: "{{ blog.title }}",
    blogUrl: "{{ blog.url }}",
    referrerUrl: document.referrer,
    referrerPath: new URL(document.referrer).pathname,
    urlHref: window.location.href,
    urlPath: window.location.pathname,
    urlHash: window.location.hash
    });
  </script>
  • Folder: Templates
  • File: article.liquid

This script tracks all your blog articles.

  <script type="text/javascript">
  window.analytics.track('Viewed Blog', {
    pageType: 'Article',
    pageTitle: document.title,
    articleTitle: "{{ article.title }}",
    articleAuthor: "{{ article.author }}",
    articleCreatedAt: "{{ article.created_at | date: "%F" }}",
    articlePublishedAt: "{{ article.published_at | date: "%F" }}",
    articleCommentCount: {{article.comments_count }},
    articleTags: ["{{ article.tags | join: '", "'}}"],
    articleUrl: "{{ article.url }}",
    referrerUrl: document.referrer,
    referrerPath: new URL(document.referrer).pathname,
    urlHref: window.location.href,
    urlPath: window.location.pathname,
    urlHash: window.location.hash
    });
  </script>

2e: Search Page

  • Folder: Templates
  • File: search.liquid

This tracks your search page.

{% if search.performed %}

<script type="text/javascript">
  analytics.track('Searched Products', {
    resultsCount: {{ search.results_count }},
    terms: "{{ search.terms }}"
  });
</script>
{% endif %}

Registration (customers/register.liquid)

<script type="text/javascript">
    analytics.track('Viewed Registration');
</script>

--- Use our analytics.trackForm() method to call a "Signed Up" event on registration:

<script type="text/javascript">
var form = document.querySelector('form[id="create_customer"]');
  
 analytics.trackForm(form, "Signed Up", function(form){
  var firstName = document.querySelector('input[name="customer[first_name]"]').value;
  var lastName = document.querySelector('input[name="customer[last_name]"]').value;
  var email = document.querySelector('input[name="customer[email]"]').value;

  return {
    firstName: firstName,
    lastName: lastName,
    email: email
  }
});
</script>

404 Page (404.liquid)

<script type="text/javascript"> analytics.track('Viewed 404 Page'); </script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment