Analytics is the foundation of every digital strategy. But the way to add Google Analytics to WordPress has changed dramatically over the years. I used to paste a simple _gaq.push script. Today, in the era of GA4, GDPR, and Consent Mode v2, things are significantly more complex.
This guide walks through every GA4 integration method with WordPress, from the simplest to the most advanced, with the European consent rules first.
How do I add Google Analytics 4 to WordPress legally in Europe?
Set the consent defaults first, load the Google tag second, and update consent only when the visitor chooses. That order is the setup. The legal reason differs by country, so here is what the primary sources say.
What UK and Irish rules require
- UK. Regulation 6(1) of the Privacy and Electronic Communications Regulations (PECR) says a person must not store information, or gain access to information stored, in a user’s device, subject to Schedule A1. The Data (Use and Access) Act 2025 put that wording in place, and the revised text on legislation.gov.uk is dated 5 February 2026.
- UK statistics exception. Schedule A1, paragraph 5 allows storage or access without consent when its sole purpose is collecting statistics about how your own service is used, to improve it. Four conditions apply: the data is not shared except to help you improve the service, the visitor gets clear and comprehensive information, the visitor has a simple, free way to object, and does not object. Whether a default GA4 setup meets the “not shared” condition depends on your data-sharing settings.
- Ireland. The Data Protection Commission says user consent is normally required to use cookies or similar technologies, that GDPR consent must be “a clear, affirmative act, freely given, specific, informed, and unambiguous”, and that only strictly necessary technologies are exempt. It cites regulations 5(3) and 5(5) of the ePrivacy Regulations.
- Google’s own condition. Google’s EU user consent policy covers end users in the EEA, the UK and Switzerland. It requires legally valid consent for cookies or local storage where the law requires it, records of consent, and clear instructions for revoking it. Google may limit or suspend the product if you do not comply.
For a typical business site, the safe route is consent before GA4 stores anything. Check the UK statistics exception against your own configuration before relying on it.
Consent mode: defaults before the tag
Google’s consent documentation is specific about order. Call gtag('consent', 'default', ...) on every page “before any commands that send measurement data (such as config or event)”. If the consent code runs out of order, the defaults do not work. For a banner that loads asynchronously, wait_for_update tells tags how many milliseconds to wait for the update call.
Consent mode does not store the visitor’s choice. Your banner has to remember it and send the update as soon as the visitor interacts.
Basic and advanced differ in when the tag loads, per Google Analytics Help:
| Basic | Advanced | |
|---|---|---|
| Google tags before consent | Blocked | Load |
| Visitor declines | Nothing is sent | Tags send cookieless pings |
| Behavioral modeling in GA4 | Not available | Available |
| Fits | Strictest reading of consent | Sites that want modeled data for decliners |
Which one is lawful for you is a legal decision, not a technical one. Basic is the stricter choice, and it is what I pick when a client has no legal advice either way.
Site Kit or Tag Manager
- Site Kit. Its consent mode setting adds the default consent tag. It does not provide a banner. You need a consent plugin and the WP Consent API plugin, and Site Kit names Complianz, Cookiebot and CookieYes as native integrations. With consent mode on, visitors from the EEA, Switzerland and the UK are not tracked by default until they consent.
- Tag Manager. Google recommends a consent management platform to handle updates and says to load your own banner through the container. In Tag Manager, use the
setDefaultConsentStateandupdateConsentStateAPIs, notgtag('consent', 'update', ...), because queued gtag commands may not be processed before the next event. - Region defaults. You can scope a default to ISO 3166-2 regions, and the most specific region wins. A default without a region covers every visitor not matched elsewhere. Give those visitors a way to change their choice.
GA4 settings that matter
- Data retention. In Admin, open Data Settings, then Data Retention, and pick 2 or 14 months for event data. You need the Editor role. Age, gender and interest data always keeps the two-month period. Google’s page does not state the default for the property setting, so open the screen and check it.
- IP addresses. Google states that in GA4 IP addresses are not logged or stored. The
anonymize_ipparameter is a Universal Analytics setting, so I removed it from the snippets below. - Data redaction. GA4 can strip email addresses and chosen URL query parameters before data is sent. Google notes the responsibility for compliance stays with whoever collects the data.
Checklist
- Choose one consent banner that supports consent mode and records consent.
- Output the
gtag('consent', 'default', ...)call first, with all four signals set todeniedfor EEA, UK and Swiss visitors. - Load GTM or the Google tag only after that call.
- Send the update the moment the visitor chooses, and store the choice.
- Make rejecting as easy as accepting. That is my practice.
- Load one GA4 source only, either Site Kit or GTM.
- Set event data retention, then test in DebugView with consent denied and granted.
- Name Google and any other recipient in the privacy policy, as Google’s policy asks.
I set this up for clients on WordPress, including the consent defaults and GTM. See my WordPress developer page or write to me through the contact form.
Add Google Analytics to WordPress with a plugin
If you don’t want to mess with code, use a plugin. It’s the simplest method but has limitations.
Site Kit by Google plugin for GA4
Pros:
- Official Google product
- Shows stats directly in WP dashboard
- Automatic integration with Search Console, PageSpeed Insights
- Easiest setup (a few clicks)
Cons:
- Limited tag control
- No advanced tracking options
- May conflict with other plugins
Installation:
- Plugins > Add New > “Site Kit”
- Activate and connect to Google account
- Select services to connect (Analytics, Search Console)
- Done
GA4 measurement ID in Rank Math or Yoast SEO
Many SEO plugins have built-in tracking ID options. Good choice if you already use one of these plugins.
RankMath:
- RankMath > General Settings > Analytics
- Paste Measurement ID (G-XXXXXXX)
Set up GA4 with Google Tag Manager in WordPress
This is the recommended method in 2026. Instead of adding GA4 directly, add a GTM container that manages all tags.
Benefits of using Google Tag Manager for GA4
- Central Management Panel: All tags (GA4, Facebook Pixel, Hotjar, ads) in one place
- Consent Mode v2: Easy implementation required by EU law
- No Code Editing: Changes without modifying theme files
- Debugging: Built-in preview mode
- Versioning: Change history and rollback capability
How to add a GTM container to WordPress
1. Create GTM Container:
- Go to tagmanager.google.com
- Create account and container (Web)
- Copy container code (GTM-XXXXXXX)
2. Paste Code in WordPress:
// In functions.php or mu-plugin
add_action('wp_head', 'add_gtm_head', 1);
add_action('wp_body_open', 'add_gtm_body', 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-YOUR-ID');</script>
<!-- End Google Tag Manager -->
<?php
}
function add_gtm_body() {
?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-YOUR-ID"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php
}3. Configure GA4 Tag in GTM:
- In GTM: Tags > New > GA4 Configuration
- Paste Measurement ID (G-XXXXXXX)
- Trigger: All Pages
- Publish
How to set up Consent Mode v2 in GTM
Google’s EU user consent policy covers visitors in the EEA, the UK and Switzerland. Consent mode is how the Google tag learns the visitor’s choice.
What it does:
- Blocks analytics/advertising cookies by default
- After user acceptance: full tracking
- After rejection: anonymous pings (modeled data)
Implementation with GTM:
- Install cookie banner (Cookiebot, Complianz, CookieYes)
- Configure GTM integration
- Set tags to “Respect Consent State”
- Add Consent variables (analytics_storage, ad_storage)
Add the GA4 tracking code without a plugin
If you want to avoid plugins and have a simple site, add code directly.
GA4 gtag.js snippet in functions.php
add_action('wp_head', 'add_ga4_code', 1);
function add_ga4_code() {
?>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-YOUR-ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-YOUR-ID');
</script>
<?php
}GA4 gtag.js snippet with Consent Mode defaults
add_action('wp_head', 'add_ga4_with_consent', 1);
function add_ga4_with_consent() {
?>
<script>
// Default consent state - everything blocked
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('consent', 'default', {
'analytics_storage': 'denied',
'ad_storage': 'denied',
'ad_user_data': 'denied',
'ad_personalization': 'denied',
'wait_for_update': 500
});
</script>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-YOUR-ID"></script>
<script>
gtag('js', new Date());
gtag('config', 'G-YOUR-ID');
</script>
<?php
}How does server-side GA4 tracking with sGTM work?
In 2026, ad blockers and ITP (Intelligent Tracking Prevention) significantly limit client-side tracking effectiveness. The solution is Server-Side Tracking.
How server-side tracking works
- Script on page sends data to your server (not Google)
- Your server forwards data to Google Analytics
- Blockers don’t see the Google connection
Server-side GTM hosting options and costs
1. Google Tag Manager Server-Side Container:
- Requires Cloud Run (GCP) or other hosting
- Cost: ~$50-100/month for medium traffic
- Full data control
2. Stape.io (SaaS):
- Hosted sGTM
- Easier setup
- From $20/month
Benefits of server-side tracking
- Ad Blocker Resistant: ~95% data vs ~70%
- Better Accuracy: Fewer conversion losses
- First-Party Cookies: Longer cookie lifespan
- Privacy: Data passes through your server
How do I set up WooCommerce ecommerce tracking in GA4?
If you have a store, you need Enhanced E-commerce.
WooCommerce ecommerce tracking with GTM
- Data Layer: WooCommerce sends product, cart, purchase data
- GA4 E-commerce Tags: Configure in GTM
- Events: view_item, add_to_cart, purchase
WooCommerce plugins for GA4 ecommerce tracking
GTM4WP (Premium) or Monster Insights (Pro):
- Automatic Data Layer integration
- Ready-made tag templates
- Conversion tracking without coding
How to check if GA4 is working
Tools to test GA4 tracking
- Google Tag Assistant: Chrome Extension
- GTM Preview Mode: Preview mode
- GA4 DebugView: Real-time in GA4
- Network Tab: Check if requests are sent
Common GA4 tracking problems and fixes
1. Double Tracking:
- Symptom: 200% pageviews
- Cause: Two GA4 tags (e.g., Site Kit + GTM)
- Solution: Remove one source
2. No Data:
- Symptom: 0 users
- Cause: Consent blocked / wrong ID
- Solution: Check Consent Mode and Measurement ID
3. GDPR Non-Compliance:
- Symptom: Tracking before consent
- Cause: No Consent Mode
- Solution: Implement Consent Mode v2
Why does Google traffic show as direct in GA4?
Update, . On 12 November 2026 Google published a page on identifying traffic from Google Search. It lists the Referer each surface sends:
- Google Search on the web:
https://www.google.com/or a local domain such ashttps://www.google.co.uk/. - Google app on Android:
android-app://com.google.android.googlequicksearchbox/https/www.google.comwhen the link opens in a browser tab, otherwise thehttps://www.google.com/form. - Google app on iOS:
https://www.google.com/or a local domain. - Discover, Images and other Google services use the same values as the surface where the person saw the link.
The Referer carries only scheme and host, never the query. It can also vanish: Google names private browsing, privacy extensions, client-side redirects (JavaScript or meta refresh), redirects that drop the query string and a redirect response that sends a stricter Referrer-Policy. When it vanishes, GA4 files the visit under direct. I check in this order:
- See every hop and its header:
curl -sIL https://your-domain.tld/ | grep -iE "^(HTTP|location|referrer-policy)". - Read the
Referrer-Policyon each redirect hop. Per MDN,no-referrersends no Referer,same-originsends none to another origin,originsends only the origin, andstrict-origin-when-cross-origin(the browser default) sends the origin between HTTPS pages. - Count the hops.
httptohttps, non-wwwtowwwand a trailing slash should be one 301, with no JavaScript ormeta refreshredirect and with the query string kept. - If the header is set, find where. Cloudflare Response Header Transform Rules can set response headers; a security or headers plugin and the server config can too. Check the response, not the configuration, and change it where it is set.
- In GA4 look at referral exclusions and custom channel rules. In server logs count only landing-page requests, because images, CSS and scripts send your own page as the Referer.
Expect a gap against Search Console even when everything is clean: consent choices and blocked scripts hide some visits, and Search Console leaves out Google Ads clicks. For a second pair of eyes on redirects and headers, see SEO and GEO optimization.
Should I load gtag.js directly or use Google Tag Manager?
In modern WordPress engineering, tracking user interactions with Google Analytics 4 requires a disciplined architectural approach. Historically, developers injected raw script snippets directly into header templates or relied on monolithic plugins that obscured tracking logic. As web performance metrics such as Interaction to Next Paint (INP) and Largest Contentful Paint (LCP) dictate search visibility, and privacy regulations across the European Union require explicit consent verification prior to reading device storage, client-side tracking requires rigorous implementation standards.
Direct gtag.js script loading versus Google Tag Manager represents the first major architectural choice for engineering teams. Direct gtag.js loading operates through a compact JavaScript library that communicates directly with Google measurement endpoints. Because gtag.js loads a minimal payload without container compilation or variable evaluation routines, it produces lower main-thread blocking time compared to a full Tag Manager container. When an enterprise platform only requires pageview tracking, standard conversion signals, and predictable outbound link monitoring, direct gtag.js loading provides an optimal performance profile.
Conversely, Google Tag Manager container deployment remains the standard for organizations managing multi-channel attribution and continuous marketing testing. Tag Manager introduces an abstraction layer where tags, triggers, and variables evaluate incoming events before forwarding them to third-party destinations. While GTM adds approximately 30 to 45 kilobytes of compressed JavaScript and demands parsing time on mobile devices, it decouples deployment velocity from software release cycles. Marketing and analytics teams can deploy conversion pixels, test trigger logic, and restructure event parameters without requesting code releases or database migrations.
Evaluating the operational trade-offs clarifies the boundary between both architectures:
| Architectural dimension | Direct gtag.js integration | Google Tag Manager web container |
|---|---|---|
| Script payload overhead | Approximately 18 to 22 KB compressed | Approximately 35 to 50 KB container payload |
| Main-thread execution time | Minimal, direct execution of config calls | Variable, evaluated per tag firing and DOM trigger |
| Deployment workflow | Version-controlled PHP and theme deployment | Browser-based GUI container publication |
| Content Security Policy complexity | Single static script host and inline config | Dynamic tag injection requiring broad directives |
| Consent Mode v2 integration | Programmatic gtag calls in theme scripts | Native GTM consent settings and community templates |
| Multi-vendor tracking | Separate inline code per advertising vendor | Consolidated multi-vendor tag orchestration |
For high-traffic publishing networks and headless commerce storefronts where Core Web Vitals directly influence organic rankings, direct gtag.js deployment minimizes Total Blocking Time (TBT). For enterprise e-commerce platforms with dozens of ad-network integrations, GTM provides the governance framework necessary to manage tags systematically.
Update, . On 17 November 2026 Google announced in the Tag Manager release notes that the Google tag and Tag Manager are being unified. Every Google tag becomes a Tag Manager container, so a site that only runs gtag.js gains Tag Manager’s interface, debugging and version control. The tag’s in-page behaviour does not change. New deployment snippets will all be identical and will not contain the gtag('config') command; initialisation is set with the Initialization trigger, which can also wait for config if you want to keep the legacy setup. On WordPress, check whether your theme or a plugin loads a G- or AW- ID through the gtm.js snippet and appends gtag('config') to it. Google calls this an unsupported installation: such sites receive the upgrade in January 2027 and the tag may start behaving differently. The fix is the standard gtag.js snippet, or gtm.js with your GTM- ID and the Google tag configured inside Tag Manager.
How do I load GA4 with wp_enqueue_script and wp_add_inline_script?
A persistent vulnerability in WordPress implementations is the insertion of raw tracking scripts directly into template files or via generic unhooked output. Using raw output statements inside header templates breaks script dependency trees, prevents proper hook ordering, and prevents automated script attribute manipulation by performance or security plugins.
The professional standard requires leveraging the WordPress enqueue pipeline. Through wp_enqueue_script, WordPress registers the external Google tag library, while wp_add_inline_script attaches configuration routines and consent commands directly before or after the handle. WordPress 6.3 introduced formal support for script loading strategies via the $args array in wp_register_script and wp_enqueue_script, allowing developers to declare strategy => 'async' or strategy => 'defer' natively.
Consider the following implementation demonstrating production-grade enqueueing with explicit dependency management and async execution:
add_action('wp_enqueue_scripts', function (): void {
$measurement_id = 'G-XXXXXXXXXX';
// Register Google tag library with explicit async execution strategy
wp_register_script(
'google-tag-platform',
'https://www.googletagmanager.com/gtag/js?id=' . rawurlencode($measurement_id),
[],
null,
[
'strategy' => 'async',
'in_footer' => false,
]
);
// Prepare initial inline configuration script
$inline_config = sprintf(
'window.dataLayer = window.dataLayer || [];' . "\n" .
'function gtag(){dataLayer.push(arguments);}' . "\n" .
'gtag("js", new Date());' . "\n" .
'gtag("config", "%s", {' . "\n" .
' send_page_view: true,' . "\n" .
' cookie_flags: "SameSite=None;Secure"' . "\n" .
'});',
esc_js($measurement_id)
);
// Attach configuration inline script before or after the main library
wp_add_inline_script('google-tag-platform', $inline_config, 'after');
wp_enqueue_script('google-tag-platform');
}, 10);When deploying Google Tag Manager instead of direct gtag.js, script registration follows an equivalent architectural discipline. While GTM documentation historically recommended pasting raw script blocks immediately following the opening head tag and a noscript iframe following the body tag, modern WordPress themes expose the wp_body_open hook to standardize body-level injection.
add_action('wp_head', function (): void {
$container_id = 'GTM-XXXXXXX';
?>
<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($container_id); ?>');
</script>
<?php
}, 1);
add_action('wp_body_open', function (): void {
$container_id = 'GTM-XXXXXXX';
?>
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=<?php echo esc_attr($container_id); ?>"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<?php
}, 1);Hook priority 1 guarantees that the dataLayer container initialization executes before plugins or interactive theme blocks attempt to push interaction events.
Can I run server-side tagging with Cloudflare Zaraz or Cloud Run?
Client-side tag execution faces structural vulnerabilities in 2026. Browser security standards, including Apple WebKit Intelligent Tracking Prevention (ITP) and Firefox Enhanced Tracking Protection (ETP), cap client-side cookie lifespans to seven days or twenty-four hours when referral parameters indicate tracking clicks. Concurrently, network-level ad blockers and privacy extensions intercept calls to Google tracking domains, leading to 15 to 30 percent data loss on tech-forward audiences.
Server-side tagging resolves these challenges by introducing a first-party proxy architecture. Instead of browser clients establishing connections with third-party Google infrastructure, the client dispatches analytics requests directly to a subdomain of the parent website, such as metrics.example.com. The server-side container inspects incoming payloads, strips sensitive headers, enriches the data with server-side context, and routes authorized events to Google Analytics over secure server-to-server APIs.
Engineering teams primarily choose between two production architectures for server-side GTM:
Google Cloud Run container clusters: Google provides open-source container images for Server-side Tag Manager (sGTM). Deployed on GCP Cloud Run behind an HTTP load balancer, these containers scale horizontally with request volume. This approach provides complete feature parity with all sGTM community templates, full control over transformation logic, and direct integration with BigQuery export pipelines. Operational costs average 40 to 120 USD monthly depending on ingress traffic and minimum instance reservations.
Cloudflare Zaraz and edge routing: For platforms already routed through Cloudflare, Cloudflare Zaraz or Cloudflare Workers can act as the edge collector. Zaraz executes analytics actions within Cloudflare edge worker nodes without loading external JavaScript libraries into the user browser. While configuration paradigms differ from native GTM workspaces, edge execution eliminates client-side JavaScript execution overhead, achieving zero impact on Total Blocking Time.
Architectural comparison of client-side and server-side tracking pipelines:
| Operational factor | Client-side tracking | Server-side Tag Manager (Cloud Run) | Cloudflare Zaraz edge |
|---|---|---|---|
| Domain context | Third-party Google endpoints | First-party custom subdomain | First-party edge interception |
| Cookie persistence | Capped by browser ITP policies | Durable HTTP-only first-party cookies | First-party session management |
| Payload governance | Browser executes black-box vendor code | Server filters PII before upstream dispatch | Edge transforms data without client scripts |
| Data recovery rate | High loss from ad blockers | Recovers 20 to 28 percent lost traffic | Recovers 22 to 30 percent lost traffic |
| Infrastructure maintenance | Zero hosting costs | Cloud container management and scaling | Cloudflare dashboard administration |
How do CSP script hashes and nonces work with GA4?
Deploying analytics scripts in security-conscious corporate environments requires integration with a strict Content Security Policy (CSP). A robust CSP header eliminates Cross-Site Scripting (XSS) vectors by explicitly defining trusted script origins, disallowing unsafe inline evaluation without validation, and enforcing cryptographic verification on all executed code.
When Google Tag Manager or gtag.js initializes, it dynamically generates inline script elements. In a strict CSP environment, the browser blocks these elements unless configured with cryptographic hashes or dynamic nonces.
Cryptographic sha256 hashes
For static inline scripts that do not vary across user sessions, teams can generate a SHA-256 digest of the script body and include it in the script-src directive:
Content-Security-Policy: default-src 'self'; script-src 'self' 'sha256-abcdef123456...' https://www.googletagmanager.com; connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com;While sha256 hashing works reliably for direct gtag configuration blocks that contain static code, it fails for Google Tag Manager containers that dynamically inject additional client tags, conversion pixels, or third-party tracking libraries.
Dynamic nonces via WordPress filters
The enterprise standard for GTM in a strict CSP environment is cryptographic nonce delivery. The web server generates a unique, cryptographically secure random token (nonce) per HTTP request. This token is passed in the CSP header and injected into every authorized script tag.
In WordPress, developers can generate nonces at runtime and distribute them across script handlers:
function get_http_csp_nonce(): string {
static $nonce = null;
if ($nonce === null) {
$nonce = base64_encode(random_bytes(16));
}
return $nonce;
}
// Attach CSP header with dynamic nonce
add_action('send_headers', function (): void {
$nonce = get_http_csp_nonce();
$csp = "default-src 'self'; " .
"script-src 'self' 'nonce-{$nonce}' 'strict-dynamic' https: http:; " .
"connect-src 'self' https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com; " .
"img-src 'self' https://*.google-analytics.com https://*.googletagmanager.com;";
header("Content-Security-Policy: {$csp}");
});
// Inject nonce into GTM script tag
add_action('wp_head', function (): void {
$nonce = get_http_csp_nonce();
$gtm_id = 'GTM-XXXXXXX';
?>
<script nonce="<?php echo esc_attr($nonce); ?>">
(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($gtm_id); ?>');
</script>
<?php
}, 1);Using strict-dynamic ensures that scripts trusted by the nonce can create new script tags without requiring individual hash approvals, resolving GTM tag loading while preserving defense-in-depth against malicious script injection.
How do I set up Consent Mode v2 for GA4?
Consent Mode v2 adds two signals to the existing storage flags: ad_user_data and ad_personalization. Google’s EU user consent policy applies to visitors in the EEA, the UK and Switzerland.
The technical requirement demands that default consent signals are declared before any tracking library loads or executes. If the default command fires after gtag.js initializes, tags may collect storage signals prematurely, violating GDPR ePrivacy principles.
The standard consent parameters comprise four primary signals:
analytics_storage: Controls access to device storage (cookies, local storage) for measurement purposes.ad_storage: Controls device storage access for advertising measurement and conversion tracking.ad_user_data: Controls whether user data (such as hashed email addresses) can be dispatched to Google for ad attribution.ad_personalization: Controls whether collected events can feed remarketing and audience targeting algorithms.
The proper initialization sequence requires outputting the consent default state at the earliest possible execution point:
add_action('wp_head', function (): void {
?>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
// Establish default consent state before tags load
gtag('consent', 'default', {
'analytics_storage': 'denied',
'ad_storage': 'denied',
'ad_user_data': 'denied',
'ad_personalization': 'denied',
'wait_for_update': 500
});
// Optional URL passthrough for cookieless attribution
gtag('set', 'url_passthrough', true);
gtag('set', 'ads_data_redaction', true);
</script>
<?php
}, 0);When a user interacts with a certified Consent Management Platform such as Cookiebot, Complianz, or CookieYes, the CMP fires an update command:
gtag('consent', 'update', {
'analytics_storage': 'granted',
'ad_storage': 'granted',
'ad_user_data': 'granted',
'ad_personalization': 'granted'
});Under Advanced Consent Mode, tags fire before consent is granted, sending cookieless pings that Google models mathematically. Under Basic Consent Mode, all tracking requests are strictly blocked until consent is explicitly confirmed.
How do I send WooCommerce dataLayer events to GA4?
Tracking e-commerce transactions in WooCommerce requires dispatching structured dataLayer events formatted according to the GA4 enhanced e-commerce schema. Default WooCommerce installations do not expose dataLayer structures out of the box. Relying on screen scraping or CSS selector triggers leads to frequent data breaks during theme updates.
Developers must inject structured events into the dataLayer during key shopping milestones: view_item_list, view_item, add_to_cart, begin_checkout, and purchase.
The purchase event is critical for revenue reconciliation and conversion tracking. It must execute exactly once upon order completion. The recommended approach utilizes the woocommerce_thankyou hook, validating order state and persisting a tracking flag in order metadata to prevent duplicate transaction counts on page refreshes:
add_action('woocommerce_thankyou', function (int $order_id): void {
if (!$order_id) {
return;
}
$order = wc_get_order($order_id);
if (!$order) {
return;
}
// Guard against duplicate purchase event dispatches
if ($order->get_meta('_ga4_purchase_tracked')) {
return;
}
$items = [];
$item_index = 0;
foreach ($order->get_items() as $item) {
$product = $item->get_product();
if (!$product) {
continue;
}
$items[] = [
'item_id' => (string) $product->get_sku() ?: (string) $product->get_id(),
'item_name' => $product->get_name(),
'price' => (float) $order->get_item_subtotal($item, false, false),
'quantity' => (int) $item->get_quantity(),
'index' => $item_index++,
'item_category' => wp_strip_all_tags(wc_get_product_category_list($product->get_id(), ', ')),
];
}
$payload = [
'event' => 'purchase',
'ecommerce' => [
'transaction_id' => (string) $order->get_order_number(),
'value' => (float) $order->get_total(),
'tax' => (float) $order->get_total_tax(),
'shipping' => (float) $order->get_shipping_total(),
'currency' => $order->get_currency(),
'items' => $items,
],
];
// Mark order as tracked to prevent double counting
$order->update_meta_data('_ga4_purchase_tracked', '1');
$order->save();
?>
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({ ecommerce: null }); // Clear previous ecommerce object
window.dataLayer.push(<?php echo wp_json_encode($payload); ?>);
</script>
<?php
}, 20);For AJAX-based cart operations, WooCommerce exposes jQuery events like added_to_cart and removed_from_cart. Modern themes using block-based carts or custom REST endpoints should trigger custom DOM events with the GA4 item payload to maintain data layer integrity across checkout steps.
Do analytics tags slow down Core Web Vitals?
Analytics scripts carry substantial client-side performance implications. A poorly configured tracking stack can degrade Core Web Vitals, causing measurable regressions in search rankings and user engagement.
Key performance hazards include:
- Main-thread CPU contention (INP degradation): When multiple marketing tags execute synchronous DOM queries and event handlers, user input interactions face noticeable delay. If a user clicks an element while GTM evaluates complex custom JavaScript variables, Interaction to Next Paint (INP) exceeds the recommended 200-millisecond threshold.
- Resource contention on Largest Contentful Paint (LCP): If tracking libraries load with render-blocking behavior in the document head, browser parsers pause CSS and hero image discovery, delaying LCP benchmarks.
- Memory leaks from unbound SPA listeners: On headless or single-page WordPress architectures, failing to detach event listeners across page transitions results in memory leaks and sluggish mobile performance.
Optimization checklist for high-performance tracking:
| Performance optimization | Implementation technique | Impact on Core Web Vitals |
|---|---|---|
| Script execution strategy | Use async strategy or delayed execution | Prevents render blocking, protects LCP |
| Tag minimization | Audit and remove unused vendor pixels quarterly | Lowers main-thread CPU time, improves INP |
| Server-side offloading | Move transformation logic to Cloud Run sGTM | Reduces client JavaScript weight by 40 to 70 percent |
| Scroll and timer limits | Avoid firing micro-events on continuous scroll | Reduces garbage collection overhead |
| Consent banner scheduling | Load CMP with high priority but non-blocking UI | Balances compliance with rapid initial render |
By implementing asynchronous script strategies, strict Consent Mode defaults, first-party server-side collection, and rigorous dataLayer sanitation, WordPress sites achieve resilient, compliant measurement without compromising speed or security.
Summary
| Method | Level | Consent Mode | Server-Side | E-commerce |
|---|---|---|---|---|
| Plugin (Site Kit) | Beginner | ✅ (with a consent plugin) | ❌ | ❌ |
| GTM Client-Side | Intermediate | ✅ | ❌ | ✅ |
| GTM + Consent Mode | Professional | ✅ | ❌ | ✅ |
| sGTM Server-Side | Expert | ✅ | ✅ | ✅ |
2026 Recommendation:
- Small sites: Site Kit or RankMath
- Business/Agencies: GTM + Consent Mode v2
- E-commerce/Enterprise: sGTM Server-Side
Don’t let your analytics data be incomplete. Invest in proper configuration, it’s the foundation of all marketing decisions.







