WordPress GTM Setup: Complete Guide (+ Troubleshooting)

Learn how to properly set up Google Tag Manager on WordPress. Covers plugin options, WooCommerce integration, caching issues, and why your GTM might not be working.

WordPressGTMWooCommerceGoogle Tag Managerplugins

Setting up Google Tag Manager on WordPress should be simple—install a plugin and go. But between caching layers, page builders, WooCommerce, and dozens of plugin options, things get complicated fast. Here’s the definitive guide to WordPress GTM setup.

Choosing Your GTM Installation Method

You have four main options for adding GTM to WordPress:

The most popular and feature-rich option.

Pros:

  • Automatic data layer for WooCommerce
  • Built-in scroll tracking, form tracking, and more
  • Active development and support
  • Free

Cons:

  • Can conflict with other tracking plugins
  • Requires proper configuration

Installation:

  1. Go to Plugins → Add New
  2. Search “GTM4WP”
  3. Install and activate “Google Tag Manager for WordPress”
  4. Go to Settings → Google Tag Manager
  5. Enter your container ID (GTM-XXXXXXX)
// GTM4WP adds the container code automatically to:
// <head> - Main GTM snippet
// <body> - Fallback noscript iframe

Option 2: Google Site Kit

Google’s official WordPress plugin that handles GA4, Search Console, and GTM.

Pros:

  • Official Google support
  • Handles multiple Google services
  • Simple setup wizard

Cons:

  • Less customization than GTM4WP
  • No automatic WooCommerce data layer
  • Heavier plugin

Installation:

  1. Plugins → Add New → Search “Site Kit by Google”
  2. Install and activate
  3. Follow the setup wizard
  4. Connect your GTM container

Option 3: Manual Installation (theme.php)

For developers who want full control.

In functions.php or a custom plugin:

// Add GTM to <head>
add_action('wp_head', 'add_gtm_head', 1);
function add_gtm_head() {
    ?>
    <!-- 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 -->
    <?php
}

// Add GTM noscript to <body>
add_action('wp_body_open', 'add_gtm_body', 1);
function add_gtm_body() {
    ?>
    <!-- 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) -->
    <?php
}

Important: Replace GTM-XXXXXXX with your actual container ID.

Some themes have “header scripts” or “footer scripts” options in the customizer.

Why we don’t recommend it:

  • Scripts may load in wrong order
  • Theme updates can remove your code
  • No <noscript> support
  • Hard to debug

If you must use this method, paste the full GTM code snippet in the header section.

WooCommerce Data Layer Setup

If you’re running WooCommerce, you need a proper data layer for ecommerce tracking.

Using GTM4WP (Easiest)

  1. Go to Settings → Google Tag Manager
  2. Click the “Integration” tab
  3. Enable “WooCommerce” integration
  4. Configure tracking options:
    • Track classic ecommerce: Enable
    • Track enhanced ecommerce: Enable

GTM4WP automatically pushes these events:

// Product views
dataLayer.push({
  'event': 'gtm4wp.productClickEEC',
  'ecommerce': {
    'click': {
      'products': [{
        'id': '123',
        'name': 'Product Name',
        'price': '29.99'
      }]
    }
  }
});

// Add to cart
dataLayer.push({
  'event': 'gtm4wp.addProductToCartEEC',
  'ecommerce': {
    'add': {
      'products': [...]
    }
  }
});

// Purchase
dataLayer.push({
  'event': 'gtm4wp.orderCompletedEEC',
  'ecommerce': {
    'purchase': {
      'actionField': {
        'id': 'ORDER123',
        'revenue': '99.99'
      },
      'products': [...]
    }
  }
});

Manual WooCommerce Data Layer

If not using GTM4WP, add this to your theme’s functions.php:

// Product page data layer
add_action('woocommerce_after_single_product', 'add_product_data_layer');
function add_product_data_layer() {
    global $product;
    ?>
    <script>
    dataLayer.push({
        'event': 'view_item',
        'ecommerce': {
            'items': [{
                'item_id': '<?php echo $product->get_sku(); ?>',
                'item_name': '<?php echo esc_js($product->get_name()); ?>',
                'price': <?php echo $product->get_price(); ?>,
                'item_category': '<?php echo esc_js(wc_get_product_category_list($product->get_id())); ?>'
            }]
        }
    });
    </script>
    <?php
}

// Order confirmation data layer
add_action('woocommerce_thankyou', 'add_purchase_data_layer');
function add_purchase_data_layer($order_id) {
    $order = wc_get_order($order_id);
    $items = array();

    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        $items[] = array(
            'item_id' => $product->get_sku(),
            'item_name' => $item->get_name(),
            'price' => $order->get_item_total($item, false),
            'quantity' => $item->get_quantity()
        );
    }
    ?>
    <script>
    dataLayer.push({
        'event': 'purchase',
        'ecommerce': {
            'transaction_id': '<?php echo $order_id; ?>',
            'value': <?php echo $order->get_total(); ?>,
            'currency': '<?php echo $order->get_currency(); ?>',
            'tax': <?php echo $order->get_total_tax(); ?>,
            'shipping': <?php echo $order->get_shipping_total(); ?>,
            'items': <?php echo json_encode($items); ?>
        }
    });
    </script>
    <?php
}

WordPress GTM Not Working: Common Issues

Issue 1: Caching Plugins Breaking GTM

The #1 cause of WordPress GTM failures. Caching plugins can:

  • Serve old pages without GTM
  • Combine/minify scripts incorrectly
  • Delay GTM loading

Solution:

  1. Exclude GTM from optimization:

For WP Rocket:

Settings → File Optimization → Exclude files from Minification
Add: googletagmanager.com

For W3 Total Cache:

Performance → Minify → JS → Never minify
Add: googletagmanager.com

For LiteSpeed Cache:

Settings → Page Optimization → JS Settings → Excluded
Add: googletagmanager.com
  1. Clear all caches after GTM changes

  2. Test in incognito mode

Issue 2: Page Builders Interfering

Elementor, Divi, and WPBakery can cause issues:

Elementor:

  • Uses custom DOM rendering
  • May delay data layer availability
  • Click tracking can fail on Elementor elements

Solution for Elementor:

// Wait for Elementor to initialize
jQuery(window).on('elementor/frontend/init', function() {
    dataLayer.push({'event': 'elementor_loaded'});
});

Divi:

  • Heavy JavaScript can block GTM
  • AJAX page loading may not trigger page views

Solution for Divi:

// Track Divi AJAX page views
jQuery(document).on('nfFormReady', function() {
    dataLayer.push({
        'event': 'virtual_page_view',
        'page_path': window.location.pathname
    });
});

Issue 3: wp_body_open Not Supported

Older themes don’t support the wp_body_open hook needed for the noscript fallback.

Check if supported:

// In your theme's header.php, look for:
wp_body_open();

// Or:
do_action('wp_body_open');

Fix for older themes:

Add to header.php immediately after <body>:

<?php
if (function_exists('wp_body_open')) {
    wp_body_open();
} else {
    do_action('wp_body_open');
}
?>

Issue 4: GTM Preview Mode Not Working

WordPress-specific preview mode issues:

  1. Cache serving old pages:

    • Purge all caches
    • Add ?gtm_debug=1 to bypass some caches
  2. Plugin conflicts:

    • Temporarily disable security plugins
    • Check for JavaScript errors in console
  3. Cookie restrictions:

    • GTM preview uses cookies
    • Cookie consent banners may block them

Issue 5: Security Plugins Blocking GTM

Wordfence, Sucuri, and similar plugins may block GTM:

Wordfence:

Wordfence → Firewall → Rules
Whitelist: googletagmanager.com

Sucuri:

  • Check “Blocked Scripts” in dashboard
  • Whitelist GTM domains

Issue 6: AJAX/SPA Navigation

WordPress sites using AJAX navigation (Divi, some themes):

// Track AJAX page views
jQuery(document).ajaxComplete(function(event, xhr, settings) {
    if (settings.url.indexOf('admin-ajax.php') === -1) {
        dataLayer.push({
            'event': 'virtual_pageview',
            'virtualPagePath': window.location.pathname,
            'virtualPageTitle': document.title
        });
    }
});

Verifying Your WordPress GTM Installation

Step 1: Check GTM is Loading

// In browser console:
console.log(window.google_tag_manager);
// Should return an object, not undefined

console.log(dataLayer);
// Should show an array with gtm.js event

Step 2: Network Tab Verification

  1. Open DevTools → Network
  2. Filter by “gtm”
  3. Refresh page
  4. Look for gtm.js request with 200 status

Step 3: GTM Preview Mode

  1. Open GTM → Preview
  2. Enter your WordPress site URL
  3. Verify:
    • “Container Loaded” shows your container
    • Page view events fire
    • No JavaScript errors

Step 4: Test Data Layer (WooCommerce)

// On product page:
console.log(dataLayer.filter(d => d.event && d.event.includes('product')));

// After add to cart:
console.log(dataLayer.filter(d => d.event && d.event.includes('cart')));

// On order confirmation:
console.log(dataLayer.filter(d => d.event === 'purchase'));

Best Practices for WordPress GTM

1. Use a Child Theme

Never edit parent theme files. Changes will be lost on update.

// In child theme's functions.php
add_action('wp_head', 'child_theme_gtm_head', 1);

2. Create a Custom Plugin

For portable, update-safe GTM code:

<?php
/**
 * Plugin Name: GTM Implementation
 * Description: Custom GTM setup for this site
 */

// Your GTM code here

3. Test After Every Update

WordPress core, theme, and plugin updates can break tracking. Test after each update.

4. Document Your Setup

Keep notes on:

  • Which plugin/method you’re using
  • What caching exclusions are set
  • Custom data layer additions

WordPress GTM Setup Checklist

  • GTM container ID is correct
  • GTM snippet is in <head> (not footer)
  • Noscript fallback is after <body>
  • Caching plugin excludes GTM
  • No duplicate GTM containers
  • WooCommerce data layer configured (if applicable)
  • Page view events firing on all pages
  • Preview mode works correctly
  • No JavaScript errors in console

For most WordPress sites, we recommend:

  1. GTM4WP plugin for container management
  2. WP Rocket or LiteSpeed Cache with proper exclusions
  3. Child theme for any custom data layer code
  4. Regular testing schedule after updates

Need Help With Your WordPress GTM Setup?

WordPress GTM issues are often caused by the unique combination of theme, plugins, and caching on your specific site. Generic guides can’t account for every configuration.

Get a free WordPress tracking audit and we’ll analyze your specific setup, identify conflicts, and tell you exactly what needs to be fixed.