Install Google Tag Manager on Shopware | OpsBlu Docs

Install Google Tag Manager on Shopware

How to install and configure Google Tag Manager on Shopware 6 using theme templates or plugins.

Google Tag Manager (GTM) provides a flexible way to manage all your tracking tags, analytics, and marketing pixels from one central platform. This guide covers GTM installation on Shopware 6.

Why Use GTM on Shopware?

Benefits:

  • Centralized tag management: All tracking in one place
  • No code deployments: Update tags without editing theme
  • Version control: Built-in versioning and rollback
  • Better performance: Single container load for all tags
  • Non-technical updates: Marketers can manage tags
  • Advanced targeting: Triggers, variables, and conditions
  • Preview mode: Test before publishing

Use Cases:

Prerequisites

  • Google Tag Manager account (tagmanager.google.com)
  • Access to Shopware theme files or admin panel
  • Basic understanding of Twig templating (for manual installation)

Installing GTM directly in your theme provides the most control and best performance.

Step 1: Create GTM Account and Container

  1. Go to Google Tag Manager

  2. Create Account

    • Click Create Account
    • Account Name: Your company/website name
    • Country: Select your country
    • Container name: Your website URL (e.g., yourstore.com)
    • Target platform: Web
    • Click Create
  3. Accept Terms of Service

    • Review and accept the terms
    • Click Yes
  4. Copy Container Code

    • GTM will show you two code snippets
    • Keep this page open - you'll need these codes

Step 2: Add GTM to Shopware Theme

You'll add two code snippets to your Shopware theme.

Locate Your Theme Files

Your theme files are typically located at:

/custom/plugins/YourThemeName/src/Resources/views/storefront/

Or for custom themes:

/custom/static-plugins/YourThemeName/src/Resources/views/storefront/

Create or Extend base.html.twig

Create or modify:

/custom/plugins/YourThemeName/src/Resources/views/storefront/base.html.twig

Option A: Create New base.html.twig

{% sw_extends '@Storefront/storefront/base.html.twig' %}

{# GTM Head Code #}
{% block base_script_tracking %}
    {{ parent() }}

    <!-- 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-XXXXXXX');</script>
    <!-- End Google Tag Manager -->
{% endblock %}

{# GTM Body Code #}
{% block base_body_script %}
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->

    {{ parent() }}
{% endblock %}

Replace GTM-XXXXXXX with your actual GTM Container ID (found in GTM dashboard).

Option B: Extend Existing Theme

If you already have a base.html.twig file, add the GTM blocks:

{% sw_extends '@Storefront/storefront/base.html.twig' %}

{# Your existing blocks... #}

{# Add GTM Head Code #}
{% block base_script_tracking %}
    {{ parent() }}

    <!-- 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-XXXXXXX');</script>
    <!-- End Google Tag Manager -->
{% endblock %}

{# Add GTM Body Code #}
{% block base_body_script %}
    <!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) -->

    {{ parent() }}
{% endblock %}

Step 3: Clear Cache and Compile Theme

After adding GTM code, clear Shopware's cache:

# SSH into your server, then run:

# Clear cache
bin/console cache:clear

# Compile theme
bin/console theme:compile

# Or both in one command
bin/console cache:clear && bin/console theme:compile

Or via Shopware Admin:

  1. Go to SettingsSystemCaches & indexes
  2. Click Clear cache
  3. Click Rebuild index

Step 4: Verify Installation

  1. Visit Your Storefront

    • Open your store in a browser
    • Open browser DevTools (F12)
  2. Check Network Tab

    • Go to Network tab
    • Filter by "gtm"
    • Look for request to googletagmanager.com/gtm.js?id=GTM-XXXXXXX
  3. Check dataLayer

    • Open Console tab
    • Type: dataLayer
    • Press Enter
    • Should see an array with GTM data
  4. Use Tag Assistant

    • Install Tag Assistant Legacy extension
    • Click extension icon
    • Should see "Google Tag Manager" detected

Method 2: Plugin Installation

Several Shopware Store plugins offer GTM integration.

Available Plugins

  1. Google Tag Manager Integration
  2. Enhanced GTM for Shopware
  3. Analytics Suite with GTM

Installation Steps

  1. Find Plugin in Shopware Store

    • Log into Shopware Administration
    • Go to ExtensionsMy extensionsExtension Store
    • Search for "Google Tag Manager" or "GTM"
    • Review features and pricing
  2. Install Plugin

    • Click on your chosen plugin
    • Click Add extension or Buy now
    • Click Install
    • Wait for installation to complete
  3. Configure Plugin

    • Go to ExtensionsMy extensionsInstalled
    • Find GTM plugin and click Configure
    • Enter your GTM Container ID (GTM-XXXXXXX)
    • Configure additional settings:
  4. Clear Cache

    bin/console cache:clear
    
  5. Test Installation

    • Visit storefront
    • Verify GTM is loading (see verification steps above)

Plugin Benefits

Pros:

  • Automatic data layer population
  • Built-in ecommerce tracking
  • Regular updates
  • Support from plugin developer
  • Easy configuration through admin

Cons:

  • Licensing costs
  • Dependent on plugin updates
  • Less control over implementation
  • Potential performance impact

GTM Configuration for Shopware

Once GTM is installed, configure it for Shopware-specific tracking.

Enable Built-in Variables

In GTM, enable these built-in variables:

  1. Go to VariablesBuilt-In VariablesConfigure
  2. Enable:
    • Page URL
    • Page Hostname
    • Page Path
    • Referrer
    • Click Element
    • Click Classes
    • Click ID
    • Click Text

Create Custom Variables

Create variables for Shopware data:

Customer ID Variable

Variable Type: Data Layer Variable

  • Name: Customer ID
  • Data Layer Variable Name: customerId
  • Default Value: (not set)

Currency Code Variable

Variable Type: Data Layer Variable

  • Name: Currency Code
  • Data Layer Variable Name: currencyCode
  • Default Value: EUR

Sales Channel ID Variable

Variable Type: JavaScript Variable

  • Name: Sales Channel ID
  • Global Variable Name: salesChannelId

Integrate GTM with Shopware's cookie consent:

{% block base_script_tracking %}
    {{ parent() }}

    <script>
        // Initialize dataLayer
        window.dataLayer = window.dataLayer || [];

        // Check cookie consent before loading GTM
        const cookiePreference = getCookie('cookie-preference');

        if (cookiePreference === 'all' || cookiePreference === '1') {
            // Load GTM
            (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-XXXXXXX');
        } else {
            // Push default consent state
            window.dataLayer.push({
                'event': 'default_consent',
                'consent': {
                    'analytics': 'denied',
                    'marketing': 'denied'
                }
            });
        }

        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }

        // Listen for consent changes
        document.addEventListener('cookie-preference-updated', function(event) {
            if (event.detail.all || event.detail.analytics) {
                window.dataLayer.push({
                    'event': 'consent_update',
                    'consent': {
                        'analytics': 'granted',
                        'marketing': event.detail.marketing ? 'granted' : 'denied'
                    }
                });
            }
        });
    </script>
{% endblock %}

Setting Up Tags in GTM

1. Create GA4 Configuration Tag

Tag Configuration:

  • Tag Type: Google Analytics: GA4 Configuration
  • Measurement ID: G-XXXXXXXXXX
  • Configuration Settings: Add custom parameters as needed

Triggering:

  • Trigger: All Pages

2. Create Event Tags

For Shopware ecommerce events:

Example: Add to Cart Event

Tag Configuration:

  • Tag Type: Google Analytics: GA4 Event
  • Event Name: add_to_cart
  • Event Parameters:
    • currency: \{\{Currency Code\}\}
    • value: \{\{Product Price\}\}
    • items: \{\{Ecommerce Items\}\}

Triggering:

  • Trigger Type: Custom Event
  • Event name: addToCart

See Shopware Data Layer for all available events.

Testing GTM Installation

Use GTM Preview Mode

  1. Open GTM

    • Go to your GTM workspace
    • Click Preview button
  2. Enter Your Store URL

    • Enter your Shopware store URL
    • Click Connect
  3. Navigate Your Store

    • GTM Tag Assistant opens
    • Navigate through your store
    • Watch tags fire in real-time
  4. Verify Events

    • Check all tags fire correctly
    • Verify variable values
    • Test triggers
    • Check data layer values

Verify in GA4

If you've set up GA4 through GTM:

  1. Open GA4 DebugView

    • Go to GA4 property
    • AdminDebugView
  2. Navigate Your Store

    • With GTM Preview active
    • Browse your store
    • Events should appear in DebugView
  3. Check Realtime Reports

    • Go to ReportsRealtime
    • Verify events appear
    • Check parameter values

Troubleshooting

GTM Container Not Loading

Check:

  • Container ID is correct (GTM-XXXXXXX format)
  • Code is in correct Twig blocks
  • Cache is cleared
  • Theme is compiled
  • No JavaScript errors in console

Debug:

// Check if GTM loaded
console.log(window.google_tag_manager);

// Check dataLayer exists
console.log(window.dataLayer);

Tags Not Firing

Common Causes:

  • Trigger conditions not met
  • Variables not defined
  • Cookie consent not granted
  • Data layer events not pushed

Solution:

  • Use GTM Preview mode
  • Check trigger conditions
  • Verify variable values
  • Check data layer in console

Cache Issues

Problem: Changes not appearing on storefront.

Solution:

# Clear all caches
bin/console cache:clear

# Warm up cache
bin/console cache:warmup

# Recompile theme
bin/console theme:compile

# Clear HTTP cache
bin/console http:cache:clear

Data Layer Not Populating

Issue: Data layer variables are empty.

Check:

  • Shopware events are firing
  • Variable names match data layer
  • Data is available on page
  • JavaScript errors aren't blocking execution

Debug:

// Monitor data layer pushes
(function() {
    const originalPush = window.dataLayer.push;
    window.dataLayer.push = function() {
        console.log('dataLayer.push:', arguments);
        return originalPush.apply(window.dataLayer, arguments);
    };
})();

Multi-Domain / Multi-Sales Channel Setup

For multiple Shopware sales channels:

Method 1: Single Container, Multiple Triggers

Use one GTM container with conditional triggers:

<script>
    // Push sales channel to data layer
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'salesChannelId': '{{ context.salesChannel.id }}',
        'salesChannelName': '{{ context.salesChannel.name }}',
        'domain': '{{ app.request.host }}'
    });
</script>

Then in GTM, create triggers based on sales channel.

Method 2: Multiple Containers

Use different containers per sales channel:

{% if context.salesChannel.id == 'channel-id-1' %}
    {% set gtmId = 'GTM-AAAAAAA' %}
{% elseif context.salesChannel.id == 'channel-id-2' %}
    {% set gtmId = 'GTM-BBBBBBB' %}
{% else %}
    {% set gtmId = 'GTM-DEFAULT' %}
{% endif %}

<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','{{ gtmId }}');</script>

Performance Optimization

Async Loading (Default)

GTM loads asynchronously by default - no changes needed.

Delayed Loading

For even better performance, delay GTM load:

// Load GTM after page load
window.addEventListener('load', function() {
    setTimeout(function() {
        (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-XXXXXXX');
    }, 2000); // 2 second delay
});

Monitor Performance Impact

Check performance with Lighthouse:

  • Before GTM installation
  • After GTM installation
  • After adding tags

Monitor:

Best Practices

1. Use Descriptive Naming

  • Tags: "GA4 - Page View", "Meta - Add to Cart"
  • Triggers: "All Pages - Cookie Consent", "Checkout Complete"
  • Variables: "Product Price", "Customer ID"

2. Organize with Folders

Group related items:

  • Google Analytics tags
  • Meta Pixel tags
  • Variables by type

3. Document Changes

Use GTM's version notes:

  • What changed
  • Why it changed
  • Who requested it

4. Test Before Publishing

Always use Preview mode before publishing changes.

5. Set Up Alerts

In GA4 or other platforms, set up alerts for:

  • Tags not firing
  • Data quality issues
  • Unexpected traffic drops

Next Steps

For general GTM concepts, see Google Tag Manager Documentation.