Packages are transported in high-tech Settings

With the sunsetting of Universal Analytics (UA) on the horizon, the shift to Google Analytics 4 is understandably stressful. It doesn’t help that many of the implementation steps we’re all used to are utterly different from what we’re used to with UA.

The good news is that GA4 is loaded with new features such as the helpful funnel builder within the ‘Explorations’ that will help your e-commerce journey. If this is your first foray into Google Analytics 4 we have a Complete Guide to GA4 here, to help get you to grips with everything new in GA4.

In this article I’m going to take a much deeper dive into Google Analytics 4 and show you how to set it up for an ecommerce site, using a Shopify store as an example. From the configuration of your Shopify store to create various data layer events, to everything you’ll need inside of your Google Tag Manager container, to send your ecommerce data through to your Google Analytics 4 account, step by step. I’ll finish up by talking through how you can test and debug your Google Analytics 4 implementation.

If you’re completely unfamiliar with Google Tag Manager and Google Analytics 4, I recommend reading through our Google Tag Manager article, to learn how to set up your account and container property.

Your GA4 Configuration

To get started with your GA4 e-commerce setup, let’s jump into our example Shopify store. The first step will be to create a data layer for the various e-commerce events you might want to track, such as ‘Purchase’, ‘Add_to_Cart’ & ‘Product_View’ events, to name a few.

If you’re completely new to Google Analytics, you may find yourself already confused, wondering what I mean by ‘create a data layer’. So let’s start at the beginning…

A data layer is one of the most important aspects of data tracking and analytics. They are essentially a JavaScript object that is used to pass information from a website, in this case your Shopify store, to your Tag Manager container. The data passed in this data layer can then be used within Google Tag Manager to populate variables and activate triggers within your tag configurations.

The Purchase Data Layer

So, as mentioned, the data layer is how we send information from our website to Google Tag Manager. For example when a customer completes an order the ‘purchase’ data layer will pass variables & information about the order to GTM.

Variables & information such as total revenue, tax, shipping, payment type, etc, are the data points we’ll want to track.

To create and setup the ‘purchase’ data layer there are four main steps:

  • Adding the code to the checkout page of your Shopify store
  • Creating a custom GTM event to receive the data layer information
  • Creating a data layer variable within GTM
  • Creating a new Tag in GTM to pass information to your GA4 Property

Adding the data layer code to the checkout page

As mentioned above, we’ll need to implement the code that will create the ‘purchase’ data layer within your Shopify store. Now, depending on how your store is set up and how you collect data from your store, this data layer code may vary slightly, so it might be best to chat to your web developer at this stage.

Below is an example code snippet that will create a ‘purchase’ data layer event that will pass the relevant order information into the data layer from your Shopify store. This code snippet was originally created by Analyzify and edited by Adam Gorecki.

{% if first_time_accessed %}
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'page_type': 'purchase',
'event': 'GA4_Purchase', //create a custom event in GTM
'transaction_id': '{{ order.name || order.order_number }}',
'totalValue': {{ total_price | money_without_currency | remove:',' }}, // Includes tax & shipping
'subtotalValue': {{ subtotal_price | money_without_currency | remove:',' }},
'tax': {{ tax_price | money_without_currency | remove:',' }},
'shipping': {{ shipping_price | money_without_currency | remove:',' }},
'currency': '{{ shop.currency }}',
'payment_type': '{{ order.transactions[0].gateway }}', //optional parameter
'items': [
{% for line_item in line_items %}
{
'item_id': '{{ line_item.sku || line_item.product_id }}', //if no SKU exists, use product Id
'item_name': '{{ line_item.product.title }}',
'discount': {{ line_item.line_level_total_discount | money_without_currency }},
'item_variant': '{{ line_item.variant.title }}',
'price': {{ line_item.final_price | money_without_currency }},
'quantity': {{ line_item.quantity }}
},
{% endfor %}
]
});
</script>
{% endif %}
Debugging Note: When copying code directly from the snippets, ensure that the code syntax matches your site's code requirements. I.e check, quote marks '', apostrophes ; , etc.

This ‘purchase’ data layer will pass the following information:

  • A custom event called ‘GA4_Purchase’
  • The Shopify transaction ID
  • The total value of the completed order
  • The subtotal of the products purchased
  • The amount of tax paid
  • The total cost of shipping
  • The type of currency used
  • The payment method used
  • The items purchased

You may wish to adjust the name of the custom data layer event to fit the name of the property you are working on, or to a more universal name. If this is the case simply navigate to the ‘event’: ‘GA4_Purchase’ line, and edit ‘GA4_Purchase’ to match your needs.

This code will need to be placed inside the ‘Checkout’ page of your Shopify store. To find the ‘Checkout’ page navigate to the Admin Settings in the far bottom left corner of your store, select ‘Checkout’ from the left-hand navigation, scroll down to the ‘Order Status Page’ and paste the code snippet inside ‘Additional Scripts’. Whilst you’re here you’ll want to make sure you have included your GTM container snippet at the very top of ‘Additional Scripts’, such that the data layer code is inserted below your GTM container. Click Save.

Shopify Checkout Scripts

Create a Custom ‘purchase’ event trigger in GTM

Congratulations! You’ve completed the first part, and arguably the most complicated part of your ecommerce setup. Now that you’ve got a data layer event pushing ‘purchase’ information, we’re ready to jump into GTM.

Important Note: Make sure you copy the custom event name from your data layer code, you'll need it later.

Now let’s head over to GTM, once you’ve logged into your GTM account and opened the GTM workspace/container you’re working on, navigate to the left-hand side and click Triggers. Now in the top right corner click New to create a new trigger.

You’ll want to name this trigger something related to the function of the trigger. For Example ‘Shopify Purchase Event’.

Shopify purchase trigger Config

Next, click Trigger Configuration, for the trigger type select ‘Custom Event’. For the Event Name, this will need to be the exact same as your Custom Event name used in your data layer code, so best practice here is to simply copy and paste the custom data layer event into the trigger’s event name.

If it’s not automatically, select this trigger to fire on ‘All Custom Events’, and click Save.

Shopify Purchase event

It’s wise at this point to test what we’ve set up so far. To do this, find and click the ‘Preview’ button in the top right corner of your GTM workspace. In the new window that opens, enter your website’s URL and click ‘Connect’, this will open a version of your site in Debug mode.

Once here, complete a test purchase or two. Return to Tag Assistant and in the left-hand Summary column you should see an event that matches the name of your custom data layer event, so in this case ‘GA4_Purchase’.

Click on the event, and then in the output window, click ‘Data Layer’ and you should see all the purchase related variables such as value, currency, tax etc.

If you see all this correctly, congratulations. This means you’ve successfully passed your Shopify purchase information into Google Tag Manager.

Create a data layer variable to receive purchase info

So you’ve now successfully passed our custom data layer event to GTM, the next steps are to package that information so that we can ship it off to our Google Analytics 4 account. In order to do this we’ll have to create some custom, user-defined variables within our GTM container.

In the left-hand menu click Variables, scroll down to User-Defined Variables and click ‘New’ in the top right corner. As with the custom trigger we created, the name of this custom variable will be for internal use only, but it’s best practice to use a standard name if any other people come to edit the GTM container; so something like ‘dlv-transaction_value’.

Next, click to configure and in the menu select ‘Data Layer Variable’. Now importantly the ‘Data Layer Variable Name’ must exactly match the diction used in your data layer code, so in this case we’ll use ‘totalValue’ (without the quote marks). Leave the rest of configurations as is and click Save.

GA4 Purchase Data layer variable

Now I’ve shown you how to create your first data layer variable, go on and complete this process for the remaining variables in your data layer code. If you’re following along, these will be:

  • transaction_id
  • totalValue
  • tax
  • shipping
  • currency
  • Payment_type
  • items
Purchase Data layer Variables

As these names need to be exact matches, it’s best practice to copy and paste them from your data layer code into your GTM variables.

Create a Tag to pass Info to GA4

You’re onto the final step. Now all that remains is sending this data that we’ve collected to our Google Analytics 4 account. To do this we’ll need to create a new tag in GTM.

In the left-hand navigation click Tags and then ‘New’ in the top right corner. Name your tag appropriately.

Click ‘Tag Configuration’ and for the tag type select ‘Google Analytics: GA4 Event’. For the ‘Configuration Tag’ select your GA4 configuration/tracking tag. For the ‘Event Name’, this will be the name of the event you pass to GA4, so it’s recommended to use something identifiable like ‘Shopify Purchase’.

Shopify Purchase Tag Config

Next we’ll want to configure our tag to pass along all our custom data layer variables. Click to expand the ‘Event Parameters’ and click to add seven rows, or parameters. Each one of these parameters will contain a data layer variable, so assign the ‘Parameter Name’, the ‘Value’ will be the corresponding custom data layer variable we made in step 2.3.

For the trigger, assign the custom trigger we made in step 2.2. Now click to save your new tag.

Here’s an example of your final tag configuration if you’ve been following along.

Shopify Purchase Tag Full Config

Return to the Workspace view, navigate to the top right corner and click Submit, publish your work to set it live and voila. You’ve set up your first ecommerce event to track purchase conversions in GA4.

The Product View Data Layer

So now you’ve got the basics down, let’s carry on and set up a ‘Product View’ data layer event.

Adding the Product View Data Layer Code to Your Store

Now this can be slightly trickier than the ‘purchase’ data layer as we need to directly edit your Shopify store’s Theme files. But don’t worry, I’ll walk you through step by step.

In the left-hand navigation of your Shopify store, click Themes, find your active or current theme, click the three dots to open a drop down and click Edit Code.

Shopify Edit Theme Code

Don’t be too worried about making any mistakes as Shopify automatically saves change history.

What we’re doing is adding a custom data layer event that will run on every product page. This will pass the product data, eventually, to our GA4 account.

To do this, in the left-hand menu, find the ‘Snippets’ folder, click ‘Add a new snippet’. For the purpose of this name the file ‘GTM-product-datalayer.liquid’. Below I’ve included an example data layer code snippet, sourced from Search Engine Journal.

<script type="text/javascript">
  window.dataLayer = window.dataLayer || [];

  window.appStart = function(){
    {% assign template_name = template.name %}

    window.productPageHandle = function(){
      var productName = "{{ product.title | remove: "'" | remove: '"' }}";
      var productId = "{{ product.id }}";
      var productPrice = "{{ product.price | money_without_currency }}";
      var productBrand = "{{ product.vendor | remove: "'" | remove: '"' }}";
      var productCollection = "{{ product.collections.first.title | remove: "'" | remove: '"' }}";

      window.dataLayer.push({
        event: 'GA4_productDetail',
        productName: productName,
        productId: productId,
        productPrice: productPrice,
        productBrand: productBrand,
        productCategory: productCollection,
      });
    };

    {% case template_name %}
    {% when 'product' %}
      productPageHandle()
    {% endcase %}
  }

  appStart();
</script>

Copy and paste the example code into the ‘GTM-product-datalayer’ snippet, click Save in the top right corner.

Including the Product View Data Layer Code in the Theme Files

Now we’ve created our ‘Product View’ data layer event, we need a way to run it on our site. To do this navigate to your ‘theme.liquid’ file, usually inside the Layout folder. Use ctrl+f, or cmd+f on mac, to open the search function; search for ‘/head’ and paste the following code directly above it:

{% render 'GTM-product-datalayer.liquid' %}

Important: if you named your code snippet differently, enter that file name instead of ‘GTM-product-datalayer.liquid’.

Click to save your work.

Creating a Product View Data Trigger in GTM

Let’s now jump back into GTM to create our custom trigger to receive our data layer event.

Navigate to the Triggers list in the left-hand navigation, and click ‘New’ to create a new trigger. To configure this trigger, select ‘Custom Event’ under ‘Other’ in the trigger type menu. Now importantly, as with the ‘purchase’ trigger, the ‘Event Name’ needs to exactly match the name of the data layer event from the code snippet, so it’s safest to copy and paste from the code into your GTM trigger, in this case we’ll use ‘GA4_productDetail’.

GA4 Product Detail Trigger

Set your trigger to fire on ‘All Custom Events’ and click Save.

Creating Data Layer Variables to Receive Product View Info

Now, in the same way we used custom defined variables to store the purchase data layer information, we’ll need to create a new set of data layer variables to store the ‘Product View’ data layer information.

Navigate to the Variables menu in GTM and down to User-Defined Variables, click ‘New’ to create our new variables. Once again, these variables will be for internal use only but it’s best practice to name them appropriately for your workspace, for example ‘dlv-productName’.

We’ll be configuring these variables the same as we did before in section 2.3, so click ‘Variable Configuration’ and select ‘Data Layer Variable’. For the ‘Data Layer Variable Name’ make sure it exactly matches the name of the variable inside the data layer code.

If you’re exactly following along, the variables you need to create are as follows:

  • productName
  • productId
  • productPrice
  • productBrand
  • productCategory

Once you’ve created all the appropriate custom variables, your ‘user-defined’ variables should contain all your purchase data layer variables and your product view data layer variables, similarly to the below screenshot.

Product View Data layer Variables

Creating the Product View Tag

Back now to Google Tag Manager, navigate to the Tags menu. Create a new tag and name it something like ‘GA4 – Product View’, set your Google Analytics Configuration Tag, set the Tag Type as ‘Google Analytics: GA4 Event’ and for the ‘Event Name’, set this as whatever event you’d like to pass to Google Analytics 4, for example we can use ‘view_item’.

GA4 Product view tag config

Just like for the purchase tag, we need to pass all the product level data to Google Analytics 4 using this tag, so under ‘Event Parameters’ add 5 rows, and populate each one with a product variable, id, name, brand, category and price. For the value of each parameter, assign the corresponding data layer variable from section 3.4 using the + icon in each row.

GA4 Product view Tag variables

For the ‘Firing Trigger’ select the custom trigger we created in section 3.3, Click Save.

If you’ve been following along exactly, below is a screenshot of what your new ‘Product View’ tag should look like.

GA4 Product View Full tag

The Add to Cart Data Layer

Moving on, another part of your ecommerce funnel you may want to track is when, and what, users add to their cart so let’s dive in.

Adding The Add to Cart Data Layer Code to the Product Page

The ‘add to cart’ data layer event will once again have us diving into the theme files of your Shopify store.

In the left-hand navigation, click Themes, find your current theme and click Edit Code in the dropdown.

Now this is where it will help if you know the setup/configuration of your website’s backend as you’ll need to locate the .liquid file that houses and controls the ‘Add to Cart’ button on your product detail pages. Likely this will be inside the product detail file itself, so ‘product.liquid’, product-template.liquid’ or something similar. You may also have a file setup that dynamically injects an ‘Add to Cart’ button onto your pages through a form or script, if you’re using a third party app such as Talon Commerce.

An easy way to find where your ‘Add to Cart’ button is located, is to find the file responsible for your product pages, and ctrl+f and search ‘data-cart’, if that fails try searching for the button script itself, by typing ‘<button class’.

Add to Cart Shopify Scripts

Once you’ve located your ‘Add to Cart’ button within your product detail file, within the <button class> copy and paste the following code:

onclick="dataLayer.push({ 'ecommerce': null });dataLayer.push({
'event': 'add_to_cart',
'ecommerce': {
        'items': [{
        'item_id': '{{ product.id }}',
        'item_name': '{{ product.title | remove: "'" | remove: '"' }}',
        'item_brand': '{{ product.vendor | remove: "'" | remove: '"' }}',
        'item_category': '{{ product.collections[0].title | remove: "'" | remove: '"' }}',
        'item_variant': '{{ product.selected_variant.sku }}',
        'currency': '{{ shop.currency }}',
        'price': '{{ product.price  | times: 0.01}}'
        }]
    }
});"

This code snippet, sourced from Benjamin at Loves Data, creates a data layer push event when a user clicks the ‘Add to Cart’ button, it then sends product-level data to the data layer that we can collect inside Google Tag Manager as we have previously.

Create an Add to Cart Trigger in GTM

Jumping back to our Google Tag Manager Container now, lets create a new trigger for our add to cart event.

Navigate to the Triggers menu, click ‘New’. Under ‘Trigger Configuration’ select ‘Custom Event’. For the ‘Event Name’, as previous, this needs to exactly match our data layer event name, so copy and paste in this case the event name, ‘add_to_cart’. Set this trigger to fire on ‘All Custom Events’ and click Save.

Add to Cart Trigger

Create Data Layer Variable to Receive Add to Cart Info

Lucky for us, we’ve already created the data layer variables we need for our ‘Add to Cart’ event, so let’s jump straight into the tag.

Add to Cart Data layer Variable

Creating the Add to Cart Tag

Navigate to the Tags menu, and click ‘New’. For the ‘Tag Type’ we want to create a ‘Google Analytics: GA4 Event’, and then select your ‘Configuration Tag’.

For the ‘Event Name’ enter something appropriate to your store, we’ll use ‘add_to_cart’. Now just as we have before, we need to set our ‘Event Parameters’ to collect the information from our data layer push, in this case you’ll want to set up:

  • Items – {{dlv-add_to_cart}}
  • productId – {{dlv-productId}}
  • productName – {{dlv-productName}}
  • productBrand – {{dlv-productBrand}}

Select the ‘Firing Trigger’ we created in 4.2, click ‘Save’ and your ‘Add to Cart’ tag should look similar to the below Screenshot.

Add to Cart Tag

The Remove from Cart Data Layer

If we’re tracking ‘Add to Cart’ events, we probably also want to track ‘Remove from Cart’ events.

Adding The Remove from Cart Data Layer Code to the Cart Page

Navigate once again to your Shopify store’s theme files, and this time locate your ‘cart’ or ‘cart-template’ .liquid file, or whatever .liquid file handles your store’s cart.

As we did in section 4.1, we need to find the <button> responsible for removing items from our cart. A handy way to achieve this is to go onto your cart on your Shopify store, right click whatever button removes an item, and click inspect. This should open up a window that will show the name and class of the button. Copy either the name or class of the ‘remove’ button and ctrl/cmd+f search it inside your ‘cart.liquid’ file.

Remove from Cart Shopify Scripts

Once you’ve found the button in the file, copy and paste the following code inside the <button>:

onclick="dataLayer.push({ 'ecommerce': null });dataLayer.push({
'event': 'remove_from_cart',
'ecommerce': {
        'items': [{
        'item_id': '{{ product.id }}',
        'item_name': '{{ product.title | remove: "'" | remove: '"' }}',
        'item_brand': '{{ product.vendor | remove: "'" | remove: '"' }}',
        'currency': '{{ shop.currency }}',
        'price': '{{ product.price  | times: 0.01}}'
        }]
    }
});"

Click ‘Save’ to save this file.

Create a Remove from Cart Trigger in GTM

You’ve got it at this point. Jumping back into Google Tag Manager, Create a new trigger, name it appropriately for your container. Set the trigger type to ‘Custom Event’, copy and paste the data layer event name into the ‘Event Name’ field, in this case ‘remove_from_cart’, lastly set the trigger to fire on ‘All Custom Events’.

Remove from Cart Trigger

Creating the Remove from Cart Tag

Let’s create our new tag, just as we did for ‘Add to Cart’. Create a new tag, with tag type ‘Google Analytics: GA4 Event’, set your Google Analytics ‘Configuration Tag’ and enter an appropriate ‘Event Name’. We’ll use ‘remove_from_cart’ for the purposes of this tutorial.

Now setup tag’s event parameters just like we did before:

  • Items – {{dlv-add_to_cart}}
  • productId – {{dlv-productId}}
  • productName – {{dlv-productName}}
  • productBrand – {{dlv-productBrand}}
Remove from Cart Tag

Click and select our trigger we made in 5.2 for our ‘Firing Trigger’ and click ‘Save’ in the top right corner.

Congratulations. You’ve made it through the difficult bit, one more step to setup now.

The Product Listing Page

For this final step we’ll be working entirely inside our Google Tag Manager container, so let’s go.

Create the Product Listing Page View Trigger in GTM

In order to create the trigger for the ‘Product Listing Page View’ you’ll want to know how your eCommerce website’s category (product listing page) URLs are structured. If you’re using a Shopify store, then just follow along. If not, you can still follow along; but you’ll just need to replace the collection URL structure in the trigger with your own.

So let’s create a new trigger within Google Tag Manager, but this time select ‘Page View’ for the trigger type. Now set this trigger to fire on ‘Some Page Views’ and click the ‘+’ to add a new condition. You’ll want to set two conditions, the first condition is that the ‘Page URL’ must contain ‘/collections’. This will identify all product collection pages. The second condition is the ‘Page URL’ must not contain ‘/products’, this will exclude all product detail pages from firing this trigger.

Product Listing Trigger

Create the Product Listing Page View Tag

We’re in the final stretch so let’s go and set up a new tag to track Product Listing Page Views.

Navigate to the Tags menu, and create a new ‘Google Analytics: GA4 Event’ with your Google Analytics ‘Configuration Tag’. Set the event name appropriately. We’ll use ‘view_collection’ here, set the ‘Firing Trigger’ as the trigger we made in 6.1, click ‘Save’.

Product Listing Tag

And that’s it. Now with everything setup, it’s time to test and debug to make sure everything works as intended.

Testing and Debugging

Debugging in GTM Preview Mode

Navigate to the workspace view in Google Tag Manager, and in the top right corner click ‘Preview’ to enter the Tag Assistant Debug mode. Enter your site’s URL and click ‘Connect’.

Now simply run through a series of events on your Shopify Site by viewing some product listings, selecting some products, adding them to a cart, removing them, and completing some test purchases. Make sure to fully test everything we’ve set up in this guide.

GTM Debugging SS

As you complete these events, you should see them appearing inside the Tag Assistant Summary panel. Click on the events and make sure the tags are all firing as intended. Select an event and click on the ‘Data layer’ tab, to see all the event data being pushed from your Shopify Store.

Once everything is working correctly, go back to the workspace view in Google Tag Manager and in the top right corner click ‘Submit’. Save your new container and workspace with appropriate name and description and that’s it, you’re all set up.

Testing in GA4 Reports

Allow your Google Analytics 4 property to update with all your new tags and events you’ve just created, this can sometimes take up to 24 hours. Once Google Analytics 4 has updated you’ll start seeing all of your new Shopify ecommerce data inside of the ‘Reports’ tab, where you can extract the data to create custom reports for your clients.

Migrating your Ecommerce Store to GA4 with Superb Digital

Online Shopping basket on laptop

Whilst GA4 migration can be quite straightforward for most websites, ecommerce site migrations can be very tricky because of the nature of the conversions being tracked.

Google Analytics is absolutely pivotal to understanding your ecommerce business so it’s imperative to make sure the transition from old to shiny new GA4 is as seamless as possible, with consistency in sales and website visitor data. More than that, GA4 represents a huge new opportunity for ecommerce businesses to gather more detailed and predictive data on their online operation.

It’s important, therefore, to have experts, who know GA4 and what it can do, on the job.

As an SEO agency specialising in ecommerce, we have a lot of experience migrating large, often complex ecommerce websites to Google Analytics 4. At the time of writing our team is not only in the process of migrating a number of our client’s sites to GA4, but also in training their people in how to use it.

If you’d like to find out how we can help migrate your ecommerce website onto GA4, and help grow the traffic and online sales you’re currently getting, why not book a strategy call today.

Top