Shopify GTM Integration | Blue Frog Docs

Shopify GTM Integration

Integrate Google Tag Manager with Shopify for centralized tag management.

Shopify GTM Integration

Complete guide to setting up Google Tag Manager (GTM) on your Shopify store for centralized tracking and tag management.

Overview

Google Tag Manager allows you to manage all your marketing and analytics tags from a single interface without editing your Shopify theme code. This is particularly valuable for Shopify stores where theme modifications can be complex and risky.

Why Use GTM with Shopify?

GTM provides powerful tag management benefits:

  • Centralized Management: Control all tracking from one interface
  • No Code Deploys: Add/modify tags without theme changes
  • Version Control: Track changes and roll back if needed
  • Preview Mode: Test tags before publishing
  • Advanced Triggers: Fire tags based on complex conditions
  • Ecommerce Tracking: Built-in support for enhanced ecommerce data
  • Third-party Integration: Easy integration with multiple analytics platforms

Prerequisites

Before setting up GTM on Shopify:

  1. GTM Account: Create a free account at tagmanager.google.com
  2. Container: Create a Web container for your Shopify store
  3. Admin Access: You'll need admin access to your Shopify store
  4. Theme Access: Ability to edit theme files (or use an app)

Installation Methods

This method gives you full control and doesn't require third-party apps.

Step 1: Get Your GTM Container Code

  1. Log in to Google Tag Manager
  2. Select your container
  3. Click on the container ID (e.g., GTM-XXXXXX)
  4. Copy both code snippets provided

Step 2: Install GTM in Shopify Theme

  1. In Shopify admin, go to Online Store > Themes
  2. Click Actions > Edit code on your current theme
  3. Open theme.liquid in the Layout folder
  4. Paste the first GTM snippet immediately after the opening <head> tag:
<!-- Google Tag Manager -->
<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>
<!-- End Google Tag Manager -->
  1. Paste the second GTM snippet immediately after the opening <body> tag:
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
  1. Replace GTM-XXXXXX with your actual container ID
  2. Click Save

Method 2: Using Shopify Apps

Several apps can help manage GTM installation:

  • Google Tag Manager by Shopify: Official free app
  • GTM DataLayer Plus: Provides enhanced data layer
  • Analyzify: Automated GTM and GA4 setup

Method 3: Custom Pixels (Shopify Plus)

Shopify Plus merchants can use Custom Pixels:

  1. Go to Settings > Customer events
  2. Click Add custom pixel
  3. Paste GTM container code
  4. Configure permissions and save

Data Layer Implementation

Basic Data Layer Setup

Add this code before the GTM container snippet in theme.liquid:

<script>
window.dataLayer = window.dataLayer || [];
dataLayer.push({
  'pageType': '{{ request.page_type }}',
  'customerId': '{{ customer.id }}',
  'customerEmail': '{{ customer.email | json }}',
  'customerTags': {{ customer.tags | json }}
});
</script>

Product Page Data Layer

In your product template (e.g., product.liquid or sections):

<script>
dataLayer.push({
  'event': 'productView',
  'ecommerce': {
    'detail': {
      'products': [{
        'id': '{{ product.id }}',
        'name': '{{ product.title | escape }}',
        'price': '{{ product.price | money_without_currency | remove: "," }}',
        'brand': '{{ product.vendor | escape }}',
        'category': '{{ product.type | escape }}',
        'variant': '{{ product.selected_or_first_available_variant.title | escape }}'
      }]
    }
  }
});
</script>

Add to Cart Event

Add this to your cart add button or AJAX callback:

dataLayer.push({
  'event': 'addToCart',
  'ecommerce': {
    'add': {
      'products': [{
        'id': variantId,
        'name': productName,
        'price': productPrice,
        'variant': variantTitle,
        'quantity': quantity
      }]
    }
  }
});

Checkout Events

For checkout tracking, add to checkout.liquid (Shopify Plus only):

{% if first_time_accessed %}
<script>
dataLayer.push({
  'event': 'checkout',
  'ecommerce': {
    'checkout': {
      'actionField': {'step': 1},
      'products': [
        {% for line_item in checkout.line_items %}
        {
          'id': '{{ line_item.product_id }}',
          'name': '{{ line_item.title | escape }}',
          'price': '{{ line_item.price | money_without_currency | remove: "," }}',
          'quantity': {{ line_item.quantity }}
        }{% unless forloop.last %},{% endunless %}
        {% endfor %}
      ]
    }
  }
});
</script>
{% endif %}

Purchase Tracking

Add to your thank you page (Additional Scripts in Shopify Settings):

<script>
dataLayer.push({
  'event': 'purchase',
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': '{{ order.name }}',
        'affiliation': '{{ shop.name }}',
        'revenue': '{{ total_price | money_without_currency | remove: "," }}',
        'tax': '{{ tax_price | money_without_currency | remove: "," }}',
        'shipping': '{{ shipping_price | money_without_currency | remove: "," }}'
      },
      'products': [
        {% for line_item in line_items %}
        {
          'id': '{{ line_item.product_id }}',
          'name': '{{ line_item.title | escape }}',
          'price': '{{ line_item.price | money_without_currency | remove: "," }}',
          'quantity': {{ line_item.quantity }}
        }{% unless forloop.last %},{% endunless %}
        {% endfor %}
      ]
    }
  }
});
</script>

Common GTM Tags for Shopify

Google Analytics 4 Tag

  1. In GTM, create a new GA4 Configuration tag
  2. Enter your Measurement ID
  3. Set trigger to All Pages
  4. Add ecommerce events as separate tags

Facebook Pixel Tag

  1. Create a Custom HTML tag
  2. Paste Facebook Pixel base code
  3. Trigger on All Pages
  4. Create separate tags for purchase, add to cart, etc.
  1. Create Google Ads Conversion Tracking tag
  2. Enter Conversion ID and Label
  3. Set trigger to purchase event
  4. Configure conversion value using order total variable

Common Triggers

Page View Triggers

Trigger Name Type Conditions
All Pages Page View All pages
Product Pages Page View Page Type equals product
Collection Pages Page View Page Type equals collection
Cart Page Page View Page Type equals cart
Checkout Page View Page URL contains /checkout

Event Triggers

Trigger Name Type Conditions
Add to Cart Custom Event Event equals addToCart
Purchase Custom Event Event equals purchase
Product View Custom Event Event equals productView

Built-in Variables to Enable

Enable these variables in GTM for Shopify tracking:

  • Page URL
  • Page Hostname
  • Page Path
  • Referrer
  • Click Element
  • Click Classes
  • Click ID
  • Click URL
  • Form Element
  • Form Classes
  • Form ID

Custom Variables

Product Price Variable

Type: Data Layer Variable Variable Name: ecommerce.detail.products.0.price

Order Revenue Variable

Type: Data Layer Variable Variable Name: ecommerce.purchase.actionField.revenue

Customer ID Variable

Type: Data Layer Variable Variable Name: customerId

Preview and Debug Mode

Using GTM Preview Mode

  1. In GTM, click Preview in the top-right corner
  2. Enter your Shopify store URL
  3. Click Connect
  4. A new window opens with Tag Assistant
  5. Navigate through your site to test tags

What to Check

  • All tags fire on appropriate pages
  • Data layer variables populate correctly
  • No duplicate tags firing
  • Ecommerce events contain all required data
  • Conversion tags fire only on thank you page

Debug Tips

// Check data layer in browser console
console.log(window.dataLayer);

// Monitor all GTM events
dataLayer.push = function() {
  console.log('GTM Event:', arguments);
  Array.prototype.push.apply(this, arguments);
};

Publishing Workflow

Before Publishing

  1. Test in Preview Mode: Verify all tags fire correctly
  2. Check GA4 Real-time Reports: Confirm data arrives
  3. Test Conversions: Complete a test purchase
  4. Review Tag Coverage: Ensure no pages are missing tags
  5. Check Performance: Monitor page load times

Publishing Steps

  1. Click Submit in GTM
  2. Add version name (e.g., "Added GA4 Purchase Event")
  3. Add version description
  4. Click Publish
  5. Monitor for 24-48 hours

Version Control Best Practices

  • Use descriptive version names
  • Document all changes in description
  • Keep previous version accessible
  • Test major changes in preview first
  • Publish during low-traffic periods

Ecommerce Tracking Implementation

Enhanced Ecommerce Events

Event When to Fire Required Data
Product Impressions Collection/search pages Product ID, name, price
Product Clicks Click on product Product details, list name
Product Detail Views Product page load Complete product data
Add to Cart Item added to cart Product, quantity, variant
Remove from Cart Item removed Product ID
Checkout Steps Each checkout step Products, step number
Purchase Order confirmation Order details, products

Revenue Tracking Setup

Ensure accurate revenue tracking:

  • Use money_without_currency filter
  • Remove commas from price strings
  • Convert to numeric format
  • Include tax and shipping separately
  • Track discounts and coupons

Troubleshooting

Issue Possible Cause Solution
GTM container not loading Code placement incorrect Verify snippets in <head> and <body>
Tags not firing Trigger misconfigured Check trigger conditions in Preview
Duplicate events Multiple implementations Remove redundant code/tags
Missing ecommerce data Data layer not pushed Verify data layer code placement
Checkout events not tracking Not Shopify Plus Upgrade or use Order Status page
Wrong revenue values Currency formatting Use money_without_currency filter
Tags fire on wrong pages Trigger too broad Add specific page conditions
Data layer undefined GTM loads before data layer Move data layer above GTM code
Purchase tag fires multiple times No deduplication Add transaction ID check
Customer data not captured Privacy settings Check GDPR/consent requirements

Advanced Configuration

Cross-Domain Tracking

If tracking across multiple domains:

// Add to GTM GA4 Configuration tag
{
  'linker': {
    'domains': ['yourstore.com', 'checkout.shopifyapps.com']
  }
}

User ID Tracking

Track logged-in customers:

{% if customer %}
<script>
dataLayer.push({
  'userId': '{{ customer.id }}'
});
</script>
{% endif %}

Custom Dimensions

Pass custom data to analytics:

dataLayer.push({
  'dimension1': 'customer_type',
  'dimension2': 'product_collection',
  'metric1': 'lifetime_value'
});

GDPR Compliance

Implement consent management:

// Wait for consent before loading GTM
if (getCookie('cookie_consent') === 'granted') {
  loadGTM();
}

Data Redaction

Remove sensitive data:

// Remove email from data layer
dataLayer.push({
  'customerEmail': undefined,
  'event': 'user_data_loaded'
});

Performance Optimization

Best Practices

  • Limit total number of tags (under 20 recommended)
  • Use async loading for all tags
  • Minimize custom HTML tags
  • Consolidate similar tags
  • Remove unused tags and triggers
  • Test page load impact

Monitoring Performance

// Measure GTM load time
performance.mark('gtm-start');
// After GTM loads
performance.mark('gtm-end');
performance.measure('gtm-load', 'gtm-start', 'gtm-end');

Testing Checklist

  • GTM container loads on all pages
  • Data layer populates before GTM
  • Product pages push product data
  • Add to cart events fire correctly
  • Checkout events track (if Shopify Plus)
  • Purchase event fires once per order
  • Revenue matches order total
  • All enabled tags fire successfully
  • No JavaScript console errors
  • Page load time acceptable
  • Mobile experience tested
  • Cross-browser compatibility verified

Additional Resources

// SYS.FOOTER