Articles

News

How to Set Up Google Analytics on Shopify with Google Tag Manager

TL:DR;

  • Custom Pixel Integration: Utilises Shopify’s custom pixel feature to embed Google Tag Manager (GTM) without altering theme files.
  • Enhanced Tracking Capabilities: Implements a comprehensive script that captures key e-commerce events and pushes the data to the GTM data layer for detailed analytics.
  • Preconfigured GTM Container: Offers a downloadable GTM container with predefined tags, triggers, and variables tailored for Shopify.
  • Privacy and Compliance Settings: Provides guidance on configuring privacy settings within Shopify to align with consent requirements and data protection regulations.
  • Avoiding Duplicate Tracking: Remove any previous Google Analytics implementations to prevent duplicate data collection and ensure the accuracy of analytics reports.

How to Set Up Google Analytics on Shopify with Google Tag Manager

Setting up Google Analytics on your Shopify store is crucial for understanding customer behaviour and tracking key metrics. In this guide, I’ll walk you through the process of implementing Google Analytics using Google Tag Manager via a custom pixel on Shopify. This method ensures reliability as it operates independently of your store’s theme and other files, providing a more flexible and powerful tracking setup.

Why Use a Custom Pixel?

Before we dive in, it’s worth mentioning that there are other ways to install Google Analytics on Shopify. The simplest method is through the Google & YouTube app, but this approach lacks the flexibility that Google Tag Manager offers, especially for advanced tracking. Another option involves manually adding code to your Shopify template and checkout page, but Shopify no longer recommends this approach. Instead, we will use a custom pixel, a more secure and efficient method.

Step 1: Adding a Custom Pixel in Shopify

  • Google Tag Manager on Shopify
  • Google Tag Manager on Shopify
  • Google Tag Manager on Shopify
  • Google Tag Manager on Shopify

Let’s start by navigating to Shopify. First, go to Settings and look for Customer Events in the left sidebar. Click on it. Here, you’ll find the option to add custom pixels, which allow you to track various user actions without modifying your theme files.

If you already have any existing pixels, they’ll be listed here. Click on Add Custom Pixel and give it a name—something like GTM or Google Tag Manager is a good choice for easy identification. Now, click Add Custom Pixel to proceed.

Step 2: Configuring Pixel Privacy Settings in Shopify

Once your custom pixel is created, you’ll see two sections for configuration. 

Google Tag Manager on Shopify

The first is Privacy Settings, which determines when the pixel will fire. If you’re using Shopify’s built-in cookie banner, ensure you select the appropriate setting. In my case, I’m not using Shopify’s built-in banner, so I select Permission: Not Required, allowing Google Tag Manager to fire regardless of consent settings, as my third-party consent banner manages this for me. If you’re using a third-party consent banner too, this may be the right choice for you as well.

Next, we need to configure Data Sale Settings. This lets you control when the pixel will fire if you are using Shopify’s built-in data sales opt-out page. 

Since I’m not using Shopify’s built-in data sales opt-out page, I select Data Collected Does Not Qualify As Data Sale to ensure smooth tracking.

Step 3: Adding Custom Pixel Code

Now that our Customer privacy is set up, we need to add a tracking code. I’ve already created the necessary script that tracks customer actions from adding items to the cart through to completing a purchase.

Custom Pixel Template

// GTM for Shopify Custom Pixel By Clockwork Moggy 
// Replace GTM-EXAMPLE with your GTM container ID 

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

(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-EXAMPLE');

analytics.subscribe("checkout_completed", (event) => {
  dataLayer.push({ ecommerce: null });
  const items = event.data?.checkout?.lineItems?.map((item) => {
    return {
      item_id: item.variant.product.id,
      item_name: item.variant.product.title,
      price: item.variant.price.amount,
      quantity: item.quantity
    }
  });
  dataLayer.push({
    event: "purchase",
    url: event.context.document.location.href,
    ecommerce: {
      currency: event.data?.checkout?.currencyCode,
      value: event.data?.checkout?.subtotalPrice?.amount,
      transaction_id: event.data?.checkout?.order?.id,
      coupon: event.data?.checkout?.discountAllocations,
      shipping: event.data?.checkout?.shippingLine?.price?.amount,
      tax: event.data?.checkout?.totalTax?.amount,
      items: items
    }
  });
});

analytics.subscribe("payment_info_submitted", (event) => {
  dataLayer.push({ ecommerce: null });
  const items = event.data?.checkout?.lineItems?.map((item) => {
    return {
      item_id: item.variant.product.id,
      item_name: item.variant.product.title,
      price: item.variant.price.amount,
      quantity: item.quantity
    }
  });
  dataLayer.push({
    event: "add_payment_info",
    url: event.context.document.location.href,
    ecommerce: {
      currency: event.data?.checkout?.currencyCode,
      value: event.data?.checkout?.subtotalPrice?.amount,
      items: items
    }
  });
});

analytics.subscribe("checkout_shipping_info_submitted", (event) => {
  dataLayer.push({ ecommerce: null });
  const items = event.data?.checkout?.lineItems?.map((item) => {
    return {
      item_id: item.variant.product.id,
      item_name: item.variant.product.title,
      price: item.variant.price.amount,
      quantity: item.quantity
    }
  });
  dataLayer.push({
    event: "add_shipping_info",
    url: event.context.document.location.href,
    ecommerce: {
      currency: event.data?.checkout?.currencyCode,
      value: event.data?.checkout?.subtotalPrice?.amount,
      items: items
    }
  });
});

analytics.subscribe("checkout_started", (event) => {
  dataLayer.push({ ecommerce: null });
  const items = event.data?.checkout?.lineItems?.map((item) => {
    return {
      item_id: item.variant.product.id,
      item_name: item.variant.product.title,
      price: item.variant.price.amount,
      quantity: item.quantity
    }
  });
  dataLayer.push({
    event: "begin_checkout",
    url: event.context.document.location.href,
    ecommerce: {
      currency: event.data?.checkout?.currencyCode,
      value: event.data?.checkout?.subtotalPrice?.amount,
      items: items
    }
  });
});

analytics.subscribe("cart_viewed", (event) => {
  dataLayer.push({ ecommerce: null });
  const items = event.data?.cart?.lines?.map((item) => {
    return {
      item_id: item.merchandise.product.id,
      item_name: item.merchandise.product.title,
      price: item.merchandise.price.amount,
      quantity: item.quantity
    }
  });
  dataLayer.push({
    event: "view_cart",
    url: event.context.document.location.href,
    ecommerce: {
      currency: event.data?.cart?.cost?.totalAmount?.currencyCode,
      value: event.data?.cart?.cost?.totalAmount?.amount,
      items: items
    }
  });
});

analytics.subscribe("product_added_to_cart", (event) => {
  dataLayer.push({ ecommerce: null });
  dataLayer.push({
    event: "add_to_cart",
    url: event.context.document.location.href,
    ecommerce: {
      currency: event.data?.cartLine?.cost?.totalAmount?.currencyCode,
      value: event.data?.cartLine?.cost?.totalAmount?.amount,
      items: [
      {
        item_id: event.data?.cartLine?.merchandise?.product?.id,
        item_name: event.data?.cartLine?.merchandise?.product?.title,
        price: event.data?.cartLine?.merchandise?.price?.amount,
        quantity: event.data?.cartLine?.quantity
      }
      ]
    }
  });
});

analytics.subscribe("product_viewed", (event) => {
  dataLayer.push({ ecommerce: null });
  dataLayer.push({
    event: "view_item",
    url: event.context.document.location.href,
    ecommerce: {
      currency: event.data?.productVariant?.price?.currencyCode,
      value: event.data?.productVariant?.price?.amount,
      items: [
      {
        item_id: event.data?.productVariant?.product?.id,
        item_name: event.data?.productVariant?.product?.title,
        price: event.data?.productVariant?.price?.amount,
        quantity: 1
      }
      ]
    }
  });
});

analytics.subscribe("page_viewed", (event) => {
  window.dataLayer.push({
    event: "shopify_page_view",
    url: event.context.document.location.href
  });
});

At the top of the code, we establish the data layer and include the Google Tag Manager container. Further down, we integrate standard Shopify customer events. This custom pixel is designed to push the following events to the data layer:

  • Purchase / Checkout Completed – Fires when a customer successfully completes a purchase. This purchase event includes all of the data that is required to configure tracking for Google Analytics. Including: The value of the purchase, the currency code, Transaction ID, Coupons used, Shipping costs, Tax and all the items that have been purchased.  
  • Add_payment_info / Payment Info Submitted – Captures when payment details are entered.
  • Add_shipping_info / Add Shipping Info – Captures when Shipping details are entered.
  • Begin_checkout / Begin Checkout – This fires when people move from the shop to the checkout page. 
  • View_cart/ View Cart – Captures when people visit the cart page. 
  • Add_to_cart / Add to Cart – Captures when users add a product to cart.
  • View_item / View Item – This track when people view a single product
  • Shopify_page_view

You can also customise this code further if you want to add more details or want to adjust the information that is collected on each event.  

You can also refer to Shopify’s support articles, however they haven’t provided the best solution. So I suggest, to save yourself time, you can download my preconfigured GTM container and Code Here. So you can simply copy and paste.

To ensure your setup is correctly linked to Google Tag Manager, you need to add your Google Tag Manager Container ID. Head over to Google Tag Manager, copy the Container ID from the top of the dashboard, and paste it into the relevant section of your pixel code in Shopify.

If you are using my code, replace the area in the code called ‘GTM-EXAMPLE’ with your Google Tag Manager container ID. 

Once done, click Save, then scroll down and click Connect twice to activate your custom pixel. Your custom pixel is now live on your store.  

Step 4: Setting Up Google Tag Manager

Now that our pixel is live, we need to configure tracking within Google Tag Manager.

To make setup even easier, you can simply copy and paste the Custom Pixel Code above and download my preconfigured Google Tag Manager container for seamless import

Download the Preconfigured Container

Subscribe now to download the Shopify Custom Pixel for Google Tag Manager. Once added to Shopify, you can set up Google Tag Manager to seamlessly send e-commerce data to Google Analytics.

Name

If you are using my Preconfigured Container:

  1. Open Google Tag Manager and navigate to Admin > Import Container.
  2. Select your preconfigured container for e-commerce tracking..
  3. Select Existing Workspace and then select Default Workspace
  4. Choose Merge to integrate the imported settings into your workspace. Then Select Confirm.  
  5. Open the Variables tab and locate Change GA Form Measurement ID. Here, we need to replace the placeholder ID with your Google Analytics Measurement ID.
  6. To find your Measurement ID, go to Google Analytics > Admin > Data Streams, select your stream, and copy the Measurement ID from the top-right corner. Paste this into Google Tag Manager and click Save.

Step 5: Import the container 

In most cases, we suggest selecting ‘Merge’ and ‘Rename conflicting tags, triggers and variables’ when you import the container. If in doubt, then we recommend creating a demo GTM container for testing so that you don’t accidentally modify anything. Select Existing Workspace and then select Default Workspace

Step 6: Edit the variable named ‘GA4 Measurement ID| CHANGE THIS’

The ‘Value’ of this variable needs to be the measurement ID from your GA4 property. We also recommend renaming the variable.

Make sure to save the Variable once you’ve done this.

If you are not using my Preconfigured Container:

  1. You will need to add a constant variable to Google Tag Manager for your Google Analytics ID.
  2. You will need to add a custom event trigger for each dataLayer event from your code, make sure to type the dataLayer event name exactly as it appears in the code. 

Step 5: Cleaning Up Shopify URLs

Due to how Shopify’s custom pixels work, the URLs captured by Google Tag Manager might not match your actual store URLs. Cleaning up the URLs is optional but for clearer and more manageable data you will probably want to do it.  To clean them up:

  1. In Google Tag Manager, create a new variable named Shopify Page Location.
  2. Choose Variable Configuration > Data Layer Variable.
  3. In the Data Layer Variable Name field, enter url in lowercase.
  4. Click Save.

Add this parameter to any Google Analytics Tag you use, under the parameter name page_location

Step 6: Setting Up Triggers and Tags

  1. Navigate to Triggers and create a new trigger named Shopify Page View.
  2. Select Trigger Configuration > Custom Event.
  3. Enter shopify_page_view in lowercase.
  4. Click Save.

Now, let’s set up the Google Tag:

  1. Navigate to Tags and create a new tag called Google Tag GA4 Page View
  2. Choose Google Tag as the Tag Type.
  3. Enter your GA4 Measurement ID.
  4. Click Add Parameter, enter page_location, and select the Shopify Page Location variable.
  5. Set the Triggering to Shopify Page View.
  6. Click Save.

Step 7: Publishing and Testing

Everything is now set up! Click Submit in Google Tag Manager, name the version, and hit Publish.

To test if everything is working:

  • Install the Tag Assistant Extension for Chrome – 
  • Go to your Shopify store and select the extension.
  • Go to the Troubleshoot Tag tab to check if events like View Item and e-commerce tracking data are firing correctly as you click through the website.

Alternatively, verify tracking in Google Analytics > Real-Time Reports. Here, you should see events like View Item and Checkout Completed appearing live.

Final Step: Avoid Duplicate Tracking

If you previously installed Google Analytics using another method, make sure to remove that setup to prevent duplicate event tracking.

Conclusion

Congratulations! You have successfully implemented Google Analytics on your Shopify store using Google Tag Manager and a custom pixel. With this setup, you now have comprehensive tracking of user behaviour, ensuring you can make data-driven decisions to improve your store’s performance. If you have any questions, feel free to reach out in the comments!

Leave a Reply

Discover more from Clockwork Moggy

Subscribe now to keep reading and get access to the full archive.

Continue reading