Let’s Learn How to Add Google Tag Manager to Your WordPress Theme (The Right Way)
If you’re setting up Google Tag Manager (GTM) on a WordPress site and want to do it manually — without relying on plugins — this guide will walk you through the proper, WordPress-friendly way to do it using built-in hooks.
Step 1: Add the GTM Script to the <head>
The first part of GTM’s code snippet goes in the <head>
of your site. This script is what loads your tags and triggers them.
You can add it by hooking into WordPress’s wp_head
action:
add_action('wp_head', 'add_gtm_script_head');
function add_gtm_script_head() {
echo "<!-- 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-5LMS4G9');</script>
<!-- End Google Tag Manager -->";
}
🔁 Tip: Replace
'GTM-5LMS4G9'
with your own GTM container ID.
Step 2: Add the <noscript>
Tag After the <body>
Tag
The second part of the GTM snippet is a <noscript>
iframe. It’s a fallback for users with JavaScript disabled, and should be placed right after the opening <body>
tag.
Thankfully, WordPress provides the wp_body_open
hook just for this purpose:
add_action('wp_body_open', 'add_code_on_body_open');
function add_code_on_body_open() {
echo '<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5LMS4G9"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->';
}
⚠️ Make sure your theme’s
header.php
file includes this line inside the<body>
tag:
<?php wp_body_open(); ?>
If it’s missing, the <noscript>
code won’t show up.
🧼 Why This Approach?
- Modular – Keeps code in the right places
- Update-Safe – Doesn’t modify theme files directly
- Follows WordPress Standards – Uses official hooks (
wp_head
,wp_body_open
)
Optional Enhancement: Define GTM ID Once
If you want to make future updates easier, define your GTM ID as a constant or theme setting:
define('GTM_ID', 'GTM-5LMS4G9');
Then reference it in both places. Clean, maintainable, and plugin-ready!
By placing the code this way, you’re integrating Google Tag Manager the right way — clean, safe, and future-proof.
Leave a Reply