Please feel free to contact me info@dbmarketer.com if you have any questions or need support with your Shopify website.

Through trial and error I believe I finally set up Google tag manager on my Shopify Basic website. There are a few limitations because you don’t gain full access to the checkout process, therefore you will lose steps in the checkout process.  I’ll walk you through adding GTM to Shopify.  We’ll implement Google Analytics through GTM.

Step 1 – Create a Google Analytics account.

Since this is about getting GTM on Shopify, I won’t walk you through this step.  Instead I’ll direct you to this YouTube Video
How to Create Google Analytics Account 2016 Tutorial

Step 2 – Create a Google Tag Manager account.

Again I’ll direct you to YouTube
Create Google Tag Manager Account and Install Analytics

Step 3 – Add Google Tag Manager snipped to your Shopify Theme.

In GTM you can click on your account number which will pop up the code you’ll need to add.

 

 

 

 

 

 

 

Copy the first block of code, then let’s head to Shopify where we will edit our theme and paste this into our Shopify Site. I’m hoping if you’re trying to do this yourself, you know how to get to the theme.liquid file of your site. Google tells you to paste this as high up in head tag as possible. Below is how mine looks.

 

 

 

 

We’ll take the 2nd block of code from GTM and paste that after the body tag in theme.liquid
This gets the GTM code on your website, however we still have some modifications to make in Shopify. In order to track revenue, whether this is for Google Analytics, or for other tracking pixels, we need to push the data layer to Google Tag Manager. From that we can get revenue tracking that can feed our tags.

Step 4 – Add Data layer and GTM code to the confirmation page of your checkout.

Add Data layer and GTM code to the confirmation page of your checkout.
We do this from Shopify. You want to go to Settings then checkout. You’ll navigate down to the box Additional scripts

I’ll explain my code since not all will apply to what you want to do. Part of this code is Liquid, other is Javascript. Some values are not used by Google Analytics, however I am pulling them in to use with other conversion tracking such as AdRoll, or Facebook.

{% if first_time_accessed %} //This is a liquid tag to ensure this code only fires once per visitor. If they come back to check on the order status, we do not want the conversion tracking to fire again. <script>

var lftOrders = {{ customer.orders.size }};//I’m feeing into GA and other tags if the transaction was new or repeat.  To do that I need to know how many orders this customer has.  If this was the 1st order this liquid variable would return 1.  Otherwise the value would be greater than 1.
var custType = 'repeatcustomer';
if (lftOrders == 1)
{
custType = 'newcustomer';
}

var coupons = 'None';   //Define a JS variable with a default value of none.  
{% assign lcoupons = "" %} //Define a liquid variable with a default empty string value

//We want to tell GA which coupon code(s) were used.  Shopify stores codes in an array.  We’ll want to loop through the codes and append it to the Liquid variable lcoupons.  GA is case sensitive so “Coupon” and “coupon” would show up as separate coupon codes in their Order Coupon Report.  As part of this loop process, I am converting the code to upper case.  
{% for discount in order.discounts %}  
{% assign lcoupons = lcoupons | append:  discount.code | upcase   %}
{% endfor %}

//Now to push the information as a data layer object.  This format is to support Enhanced Ecommerce tracking.  I’m also pushing some items that I don’t use in Google Analytics but I do use in other pixels.  We’ll get to that part later.  Most of the values are straight out of Shopify’s Liquid.  I’m not altering the data.  I am altering the product name.  To help distinguish between products I am prefixing the vendor’s name.  I might have 2 products named Black Hat.  I want to Prefix that with Nike - Black Hat and Adidas -Black Hat.  You can remove that and make that just ‘{{line_item.product.title}}’ if that doesn’t work for you.  

One thing I do that isn’t in this code is the revenue amount I send pixels is not “total_price”.  This is what the customer paid including taxes and shipping.  For me my block of code is
“'revenue': {{subtotal_price | times: 0.01}},”.  I prefer to track revenue based on product sales.  That is just my preference.  Also note that I am making everything lower case here as far as the names of the variables and fields.  

var dataLayer = window.dataLayer = window.dataLayer || [];
dataLayer.push(
{
'ecommerce' : {
'purchase': {
'actionField': {
'id': '{{order.order_number}}',
'revenue': {{total_price | times: 0.01}},
'subtotal': {{subtotal_price | times: 0.01}},
'tax': {{tax_price | times: 0.01}},
'shipping': {{shipping_price | times: 0.01}},
'customerType': custType,
'lifetimeOrders': lftOrders,
'email': '{{order.email}}',
'coupon': '{{ lcoupons }}'
},
'products': [
{% for line_item in line_items %}
{
'id': '{{line_item.sku}}',
'name': '{{line_item.vendor | append: ' - '  | append: line_item.product.title}}',
'category': '{{line_item.product.type}}',
'brand': '{{line_item.vendor}}',
'price': {{line_item.line_price | times: 0.01}},
'quantity': {{line_item.quantity}}
},
{% endfor %}]
}}}
);

</script> //Now that we pushed the data layer, we can call our Google Tag manager code. You’ll want to make sure the highlighted “YOURACCOUNT” values are replaced with your actual GTM account id. Or you can just copy and paste the 2 blocks of code you got out of GTM.  <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','YOURACCOUNT');</script>  <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=YOURACCOUNT" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> {% endif %} 

 

Step 5 – Set up Google Analytics for Enhanced Commerce

We want to turn on eCommerce and enable Enhanced Ecommerce reporting. You want to go to the view you want to do this for, and go to Ecommerce Settings.

 

 

 

 

 

 

While you’re in here you’ll also want to jot down your Google Analytics Tracking ID. If you go into Admin> Under Property >Tracking Info > Tracking Code. Your ID starts with “UA”. We’re going to need this ID in the next step.

Step 6 – Finalize set-up of Google Tag Manager

There are a few things we need to address.
I won’t get too much into how to use Google Tag manager, I’ll assume you know why you need Google Tag Manager. This will be more of step by step process.

1. Create a new constant user defined variable. You can follow your own naming convention. We’re going to store the Tracking ID you captured above. I named mine gaAccountID. Enter in your tracking ID as the value.
2. Create a new constant user defined variable. Name this variable gaCrossDomains. As a value, type in your domain, as well as the domain checkout.shopify.com. You should end up with something like “mywebsite.com,checkout.shopify.com” This value should be comma separated. The reason we need to do this? When customers checkout, they leave your website and end up on the checkout site. We have to tell GA to track across domains.
3. Create a new constant user defined variable. Name this variable gaDomain. The value will be “auto”
4. If you’re only planning on using Google analytics you can skip this step. If you’re planning on sending conversion data to other tags, you’ll need this step. I’ll walk you through one, you can just repeat for the others. Remember in step 4 we pushed the data layer to Google tag manager? We had ID,Revenue,Shipping etc. Well now we want to push those values into variables so we can reuse them in other tags.
a. Create a variable. The type will be Data Layer Variable. For ID (OrderID) I named mine transOrderID. I also created a variable for Revenue,Shipping,Tax,Coupon,SubTotal,Email,CustomerType. All prefixed with trans.
b. Back to transOrderID. You have to tell GTM where to get the value in the data layer. In our checkout script from Step 4, we created a data layer. To get the ID, in the field “Data Layer Variable Name”, enter in “ecommerce.purchase.actionField.id” This is all case sensitive.
c. You need to repeat this for every data layer value you are trying to reference.
5. Now we’ll create our google analytics tags and triggers. First thing we’ll do is create our Transaction Trigger. I named my trigger “Transaction”. It’s pretty simple. Navigate to triggers. We’re going to create a page view trigger type. The 2 conditions are
a. Page url matches RegEx(ignore case) https://checkout.shopify.com/(.*)/orders/(.*)thank(.*)
b. Referrer does not contain myshopify.com/admin/orders/

Step 7 – Create Google Analytics tag

We now need to finalize the Google Analytics set up. Go to Tags, Select new. For tag type you’ll select Universal Analytics. I’ll go down the list and set the values. If I didn’t mention it below, that’s because the default value is fine.
• Tracking ID : {{gaAccountID}} – This is the variable we created where we stored our TrackingID
• allowLinker: true
• cookieDomain: {gaDomain}}
• Enable Enhanced Ecommerce Features – Check
• Use data layer – Check
• Enable Display Advertising Features – Check
• Auto Link Domains: {{gaCrossDomains}}
• Use Hash as Delimiter: False
• Decorate Forms: False
Under Triggering
• Select All pages
• Select Add Exception, and select Transaction.

Step 8 – Create Google Analytics Transaction Tag

We’re going to make a copy of the tag we just created then make a small modification. Open the tag you just created and make a copy.

 

 

We’re going to leave everything the same except the Trigger. You want to remove all the triggers and excepts. Then you want to select the trigger to the Transaction trigger we initially created.

 

 

Now that you have Google tag manager installed, you can add tags as you normally would. This isn’t a Google Tag Manager tutorial, so you’ll need to figure out how you can use Google Tag Manager. You don’t need GTM to use Google Analytics on Shopify. I went this route because I wanted to customize some of the data being sent to GA. If all you’re interested in is being able to add conversion pixels, then you can skip all the Google Analytic steps. You would still add the data layer code, then populate those variables in GTM. Then as you add your conversion tags, use the variables we created in GTM to send conversion data.

I hope this helps others. Below is the checkout data layer snippet without my comments embedded.

{% if first_time_accessed %}
<script>

var lftOrders = {{ customer.orders.size }};
var custType = 'repeatcustomer';
if (lftOrders == 1)
{
custType = 'newcustomer';
}

var coupons = 'None';
{% assign lcoupons = "" %}

{% for discount in order.discounts %}
{% assign lcoupons = lcoupons | append:  discount.code | upcase   %}
{% endfor %}


var dataLayer = window.dataLayer = window.dataLayer || [];
dataLayer.push(
{
'ecommerce' : {
'purchase': {
'actionField': {
'id': '{{order.order_number}}',
'revenue': {{total_price | times: 0.01}},
'subtotal': {{subtotal_price | times: 0.01}},
'tax': {{tax_price | times: 0.01}},
'shipping': {{shipping_price | times: 0.01}},
'customerType': custType,
'lifetimeOrders': lftOrders,
'email': '{{order.email}}',
'coupon': '{{ lcoupons }}'
},
'products': [
{% for line_item in line_items %}
{
'id': '{{line_item.sku}}',
'name': '{{line_item.vendor | append: ' - '  | append: line_item.product.title}}',
'category': '{{line_item.product.type}}',
'brand': '{{line_item.vendor}}',
'price': {{line_item.line_price | times: 0.01}},
'quantity': {{line_item.quantity}}
},
{% endfor %}]
}}}
);

</script>

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>


<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> {% endif %}