TechEarl

Add Google Tag Manager to WordPress Without a Plugin

Install Google Tag Manager on WordPress with no plugin: the script in wp_head, the noscript iframe in wp_body_open (WP 5.2+), the container ID stored once, and reading GA4 data back into WordPress server-side with a service account.

Ishan KarunaratnePublished ⏱️ 15 min readUpdated
Share thisCopied
How to add Google Tag Manager to WordPress without a plugin: the GTM script injected high in the head via wp_head, and the noscript iframe injected immediately after the opening body tag via the wp_body_open hook added in WordPress 5.2.

To add Google Tag Manager to WordPress without a plugin, you inject GTM's two snippets through two hooks: the <script> snippet on wp_head (early), and the <noscript> iframe on wp_body_open (WordPress 5.2+, so it lands immediately after the opening <body> tag). Drop this into a small must-use plugin and you are done:

php
<?php
/**
 * Plugin Name: TE Google Tag Manager
 * Plugin URI:  https://techearl.com/wordpress-google-tag-manager-without-plugin
 * Description: Injects the Google Tag Manager container (head script + body noscript) without a third-party plugin.
 * Version:     1.0.0
 * Author:      Ishan Karunaratne
 * Author URI:  https://techearl.com
 * License:     GPL-2.0-or-later
 * Text Domain: te-gtm
 */

if ( ! defined( 'TE_GTM_CONTAINER_ID' ) ) {
    define( 'TE_GTM_CONTAINER_ID', 'GTM-XXXXXX' );
}

function te_gtm_head() {
    $id = TE_GTM_CONTAINER_ID;
    if ( empty( $id ) || is_admin() ) {
        return;
    }
    ?>
<!-- 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','<?php echo esc_js( $id ); ?>');</script>
<!-- End Google Tag Manager -->
    <?php
}
add_action( 'wp_head', 'te_gtm_head', 1 );

function te_gtm_body() {
    $id = TE_GTM_CONTAINER_ID;
    if ( empty( $id ) || is_admin() ) {
        return;
    }
    $src = 'https://www.googletagmanager.com/ns.html?id=' . rawurlencode( $id );
    ?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="<?php echo esc_url( $src ); ?>"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
    <?php
}
add_action( 'wp_body_open', 'te_gtm_body' );

Swap GTM-XXXXXX for your real container ID, save the file as wp-content/mu-plugins/te-google-tag-manager.php, and GTM is live. The rest of this post is why it is two snippets, why the second one is the part everyone gets wrong, what to do on a theme that predates wp_body_open, and the other direction: pulling your GA4 numbers back into WordPress server-side with a service account.

Why GTM is two snippets, not one

Google Tag Manager hands you two blocks of code, and they are not interchangeable.

The first is a <script> that loads gtm.js and sets up the dataLayer, the triggers, the variables, and every tag you have configured inside the container. Google's install guide says to put it "as high in the <head> as possible." That is why the snippet hooks wp_head at priority 1: the earlier GTM initializes, the less chance you miss an early pageview or a tag that needs to fire before the page finishes painting.

The second is a <noscript> containing an <iframe> that points at ns.html. This is the fallback for visitors with JavaScript disabled, and it has to live in the <body>. An iframe inside <head> is invalid HTML, which is exactly why GTM never gives you the option to put the noscript there. Google's guidance is specific: place it "immediately after the opening <body> tag."

So you have one snippet that wants to be as high in the head as possible, and one that has to be the first thing inside the body. Two different locations, two different hooks.

The body snippet is the part people get wrong

The head snippet is easy. WordPress has had wp_head since forever, every theme calls it, and hooking onto it at an early priority is routine.

The body snippet is where DIY GTM installs fall apart. For years there was no clean hook that fired right after <body>, so people did one of three messy things: pasted the noscript into functions.php and echoed it on some random late hook, jammed it into the footer, or hand-edited header.php to splice it in after the <body> tag. The footer and the random hook both put the noscript in the wrong place, and editing header.php ties your tracking to one theme.

WordPress 5.2 (May 2019) fixed this by adding the wp_body_open action. Core themes, and any theme updated since, call wp_body_open() immediately after their opening <body> tag. Hook your noscript onto that action and it renders in exactly the spot Google asks for, no theme file editing, no guessing.

Putting the noscript anywhere else is the common mistake. It does still "work" loosely (an iframe in the footer fires for no-JS visitors too), but Search Console's GTM container verification looks for the snippet right after <body>, and an out-of-place noscript can fail that check. Keep it on wp_body_open and you never think about it.

Store the container ID once

Notice the snippet defines the ID one time, as a constant, and both functions read TE_GTM_CONTAINER_ID. That is deliberate. The fastest way to ship a half-broken GTM install is to paste GTM-XXXXXX into the head block and a different (or typo'd) ID into the body block. Define it once and the two snippets can never drift apart.

I keep the literal in the plugin for a single-site setup, but the better home for it is wp-config.php, above the "stop editing" line:

php
define( 'TE_GTM_CONTAINER_ID', 'GTM-XXXXXX' );

With the ID in wp-config.php, the plugin's own define() becomes a fallback (the if ( ! defined(...) ) guard makes sure the config value wins), staging and production can carry different container IDs, and the ID never ends up in version control with the rest of the theme. If a non-developer needs to change it, promote it to an option instead and read it with get_option( 'te_gtm_container_id' ) so it lives in the database and gets a settings field. Either way the rule holds: one source of truth, read in two places.

Themes that do not call wp_body_open

wp_body_open only fires if the theme actually calls it. Every default Twenty-* theme since Twenty Nineteen does, and most maintained commercial themes added it years ago. But an old custom theme, or one that has not been touched since before 2019, may not, and then your noscript silently never renders.

The fix is one line in the theme's header.php, right after the opening <body> tag:

php
<body <?php body_class(); ?>>
<?php wp_body_open(); ?>

Use the function, not a hardcoded GTM noscript. wp_body_open() is what plugins and other code expect to be present, so adding the hook (rather than the tracking code itself) fixes the noscript for GTM and for anything else that relies on the hook, and your tracking stays in the plugin where it belongs.

If you genuinely cannot edit the theme, the last resort is to hook the noscript onto a late header action and accept that it will not sit exactly after <body>. It is worse for the Search Console verification case above, but better than no noscript at all. Adding the one missing wp_body_open() line is almost always the right move.

GTM is not GA4, and you should not load both raw

A point of confusion worth clearing up: Google Tag Manager is a container, not an analytics tag. By itself it collects nothing. It is a delivery system that loads and fires whatever tags you configure inside the GTM web UI: GA4, conversion pixels, custom event scripts, and so on.

gtag.js is different. That is the direct Google tag you paste straight onto the page to send data to GA4 (or Google Ads) without a container in between. So you have two valid ways to get GA4 onto a site:

  • Direct: paste the gtag.js snippet (or a GA4-specific helper) and you are sending GA4 hits with no GTM at all.
  • Through GTM: install the GTM container as above, then add a GA4 Configuration tag inside the container. GTM loads GA4 for you, and you manage every other tag from the same place.

Pick one path for GA4. If you are standing up GTM, configure GA4 as a tag inside it and do not also hardcode gtag.js on the page, or you will double-count pageviews. (If you only want GA4 and have no plans for other tags, the direct route is simpler. I cover pulling GA4's data back into WordPress further down.)

The same "pick one" rule applies to the install itself: if you add the snippets by hand as shown here, do not also run a GTM plugin that injects its own container. Two copies of the same container ID on one page is double-tagging, and it double-fires every tag. Hand-coded or plugin, never both.

Verify it actually fired

Two checks, and do both.

First, view-source on a front-end page (not the admin) and search the HTML for GTM-:

  • In the <head>, near the top, you should see the Google Tag Manager script block with your real container ID in the gtm.js?id=GTM-... URL.
  • Right after the opening <body> tag, you should see the Google Tag Manager (noscript) iframe block, also with your ID in the ns.html?id=GTM-... URL.

If the head block is there but the body block is missing, your theme is not calling wp_body_open(). That is the section above.

Second, open GTM's Preview mode (the Preview button in the container's workspace). It connects Tag Assistant to your site and shows whether the container loaded and which tags fired on each interaction. View-source proves the snippet is on the page; Preview proves the container is actually talking to Google and your tags fire. A snippet that is present but shows "not connected" in Preview usually means a wrong container ID, a page cache serving old HTML (purge it), or a consent / blocker setup intercepting the request.

On consent: if you operate anywhere that requires it, GTM should run behind a Consent Mode setup so tags hold until the visitor opts in. That is its own topic and out of scope here, but build the consent layer before you start firing marketing tags in production, not after.

Pull GA4 data into WordPress server-side

GTM pushes data out to GA4. Sometimes you want the reverse: your own GA4 numbers (a "top pages" box, a dashboard widget) read from inside WordPress with no JavaScript and no embed. For that you authenticate as a Google Cloud service account and call the GA4 Data API. The whole job is one runReport against your property ID:

php
use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;
use Google\Analytics\Data\V1beta\OrderBy;

function te_ga4_run_report( $property_id ) {
    $client = new BetaAnalyticsDataClient();

    return $client->runReport( [
        'property'   => 'properties/' . $property_id,
        'dateRanges' => [
            new DateRange( [ 'start_date' => '28daysAgo', 'end_date' => 'today' ] ),
        ],
        'dimensions' => [ new Dimension( [ 'name' => 'pagePath' ] ) ],
        'metrics'    => [ new Metric( [ 'name' => 'screenPageViews' ] ) ],
        'orderBys'   => [
            new OrderBy( [
                'metric' => new OrderBy\MetricOrderBy( [ 'metric_name' => 'screenPageViews' ] ),
                'desc'   => true,
            ] ),
        ],
        'limit'      => 10,
    ] );
}

That returns a RunReportResponse with one row per page path for the last 28 days. One warning first: the old analytics/v3 (Universal Analytics) API is gone. Universal Analytics stopped processing new data on 1 July 2023 and Google deleted the historical data a year later, so any tutorial using Google_Service_Analytics and view IDs is out of date. GA4's Data API (analyticsdata.googleapis.com) is the only option.

Create the service account and grant property access

In the Google Cloud console: pick or create a project, enable the Google Analytics Data API under "APIs & Services" → "Library", then under "IAM & Admin" → "Service Accounts" create an account (I name it wp-ga4-reader). It needs no project-level IAM role. On its "Keys" tab, "Add Key" → "Create new key" → JSON. That download is the only copy of the private key; treat it like a password, and note its client_email (wp-ga4-reader@your-project.iam.gserviceaccount.com).

Then the step people miss. In the Google Analytics admin, go to Admin → Property → "Property access management", add that client_email as a user, and give it the Viewer role. API access and property access are separate grants: a valid key with no property grant returns 403 PERMISSION_DENIED no matter how correct your code is. While you are there, copy the numeric property ID (like 123456789, not the G-XXXXXXXXXX measurement ID). That is what you pass to te_ga4_run_report().

Install the client and point it at the key

bash
composer require google/analytics-data

Load require_once __DIR__ . '/vendor/autoload.php'; once, early (in your main plugin file), and composer show google/analytics-data confirms the install. new BetaAnalyticsDataClient() with no arguments uses Application Default Credentials, reading the key path from GOOGLE_APPLICATION_CREDENTIALS. Set it at the server level (Apache SetEnv, a PHP-FPM env directive, or the container environment), pointing outside the web root:

bash
GOOGLE_APPLICATION_CREDENTIALS="/etc/secrets/wp-ga4-reader.json"

On shared hosting where you cannot set env vars, pass the path explicitly:

php
function te_ga4_client( $key_path ) {
    return new BetaAnalyticsDataClient( [
        'credentials' => $key_path,
    ] );
}

Cache the report, refresh it on a schedule

The Data API has per-property quotas and a runReport round trip adds real latency, so never call it on every page load. Cache it in a transient and only hit the API on a miss:

php
function te_ga4_top_pages( $property_id ) {
    // One cache key per property, so two properties never share a report.
    $key    = 'te_ga4_top_pages_' . preg_replace( '/[^0-9]/', '', $property_id );
    $cached = get_transient( $key );
    if ( false !== $cached ) {
        return $cached;
    }

    $pages    = [];
    $response = te_ga4_run_report( $property_id );

    foreach ( $response->getRows() as $row ) {
        $pages[] = [
            'path'  => $row->getDimensionValues()[0]->getValue(),
            'views' => (int) $row->getMetricValues()[0]->getValue(),
        ];
    }

    set_transient( $key, $pages, HOUR_IN_SECONDS );

    return $pages;
}

Better still, refresh it out of band so no visitor ever eats the API latency after the transient expires:

php
add_action( 'te_ga4_refresh_event', function () {
    delete_transient( 'te_ga4_top_pages_123456789' );
    te_ga4_top_pages( '123456789' );
} );

if ( ! wp_next_scheduled( 'te_ga4_refresh_event' ) ) {
    wp_schedule_event( time(), 'hourly', 'te_ga4_refresh_event' );
}

The cron mechanics (custom intervals, why the wp_next_scheduled guard matters, swapping WP-Cron for a real system cron on busy sites) are in scheduling a recurring task with WP-Cron. Keep the property ID and key path in wp-config.php constants so the same plugin ships unchanged across environments.

Keep the key safe, and debug the usual errors

The JSON key is a private key. Keep it outside the web root (/etc/secrets/ or one level above public_html) with chmod 600, never under wp-content/ where a directory listing or a backup zip can leak it, and add it to .gitignore before the first commit. If a key ever lands in a repo, deleting the file does not help (it is still in history): delete the key on the service account in the Cloud console, which invalidates it immediately, and create a new one.

To verify, run te_ga4_run_report() from a throwaway wp eval-file test.php and var_dump( $response->getRowCount() ). A non-zero count means the key, the API enablement and the property grant all line up. A 403 PERMISSION_DENIED is the missing property grant. A 401 UNAUTHENTICATED (invalid credentials) or "could not load default credentials" means the client never found a usable key: the path is wrong, the env var did not reach PHP-FPM, or the PHP user cannot read the file. Finally, wp cron event list should show te_ga4_refresh_event scheduled.

The first snippet is a script that loads gtm.js and initializes the container (the dataLayer, triggers, variables, and your tags). Google asks for it as high in the head as possible so it fires early.

The second is a noscript containing an iframe, the fallback for visitors with JavaScript turned off. An iframe is invalid inside head, so it has to go in the body, immediately after the opening body tag. Two locations, two snippets.

wp_body_open is an action hook added in WordPress 5.2 (May 2019). Themes call wp_body_open() immediately after their opening body tag, giving you a standard place to inject body-level code like the GTM noscript iframe.

Before 5.2 there was no clean hook for this, which is why older DIY installs edited header.php directly. Hooking the noscript onto wp_body_open puts it in the exact spot Google asks for, with no theme-file edits.

Almost always the theme does not call wp_body_open(). Older or custom themes built before WordPress 5.2 may never have added it, so the action never fires and your noscript renders nowhere.

Fix it by adding <?php wp_body_open(); ?> right after the opening body tag in the theme's header.php. Add the hook call, not a hardcoded snippet, so other code that expects the hook works too. Then re-check view-source for the ns.html iframe.

No. GTM is a container that loads and fires tags you configure inside it; on its own it collects nothing. GA4 is an analytics product, and gtag.js is the direct Google tag you paste on the page to send data to GA4 without a container.

You can run GA4 either way: paste gtag.js directly, or install GTM and add a GA4 Configuration tag inside the container. Pick one path. Doing both double-counts your pageviews.

No, that is double-tagging. If both the plugin and your hand-coded snippet inject the same container ID, the container loads twice and every tag fires twice, which inflates your data.

Choose one method. If you are coding it in via wp_head and wp_body_open as shown here, deactivate any GTM plugin. If you prefer a plugin, do not also hardcode the snippet.

Because API access and property access are two separate grants. A working key only proves which service account is calling; it grants no view of your data.

In the Google Analytics admin, open Property access management, add the service account's client_email (the ...iam.gserviceaccount.com address from the JSON), and give it the Viewer role. No project-level Cloud IAM role is needed.

See also

Sources

Authoritative references this article was fact-checked against.

TagsWordPressGoogle Tag ManagerPHPfunctions.phpAnalyticsGA4Service AccountWP-Cron

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Use Claude CLI and AI-assisted WP-CLI for WordPress: ACF field groups, Figma to ACF layouts, wp db query, log triage, audits. Real prompts, real limits.

Using Claude CLI to Manage WordPress Sites

How I use Claude CLI to run WordPress and ACF work end-to-end: ACF field group generation, WP-CLI orchestration, log triage, plugin debugging, bulk content ops, turning Figma designs into ACF Flexible Content layouts, plus the AI-assisted WP-CLI patterns (checkpoint plans, migration scripts, wp db query, audits, aliases) and what never to delegate.

Managed WordPress vs VPS for agencies: decision tree, break-even math, when to self-host, profit per client, and honest takes on Kinsta, WP Engine, Cloudways and more.

Managed WordPress Hosting vs VPS for Agencies

Managed WordPress hosting vs VPS for agencies, in one guide: a decision tree by traffic and workload, the break-even math, when self-hosting pays, how hosting drives agency profit, and honest takes on Kinsta, Rocket.net, Cloudways, WP Engine and Bluehost.

Change an EC2 instance type without data loss: stop the instance, run aws ec2 modify-instance-attribute, start it again. Covers Nitro vs Xen compatibility, ENA and NVMe driver requirements, the instance-store ephemeral-data trap, and the zero-downtime ASG rolling-replace pattern.

How to Change an AWS EC2 Instance Type (Resize Without Data Loss)

Stop the instance, modify the instance type, start it. The exact gcloud-equivalent AWS CLI syntax, the compatibility matrix for moving between families and generations, the Nitro vs Xen gotcha, the instance-store data-loss trap, and the production sequence (snapshot AMI, scale out, replace) that gets you to a new instance type with zero downtime.