Add Google Analytics 4

Loads the GA4 tag on every front-end page. Paste your Measurement ID.

Hook
wp_enqueue_scripts
Updated
2026-09-27
License
GPLv2

No consent check. On sites with EU visitors, load it through your cookie consent tool instead.

add_action( 'wp_enqueue_scripts', function() {
    $id = strtoupper( trim( 'G-XXXXXXXXXX' ) );
    if ( 'G-XXXXXXXXXX' === $id || ! preg_match( '/^G-[A-Z0-9]+$/', $id ) ) {
        return; // No valid Measurement ID yet.
    }
    if ( current_user_can( 'manage_options' ) ) {
        return; // Keep your own visits out of the reports.
    }
    wp_enqueue_script( 'ga4', 'https://www.googletagmanager.com/gtag/js?id=' . $id, array(), null, array( 'strategy' => 'async' ) );
    wp_add_inline_script( 'ga4', "window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config','" . $id . "');", 'before' );
} );

These are the default values. Change them in the builder before you copy. Licensed under GPL-2.0-or-later, provided as is. Review and test it before using it on a live site.

How it works

The snippet loads Google’s gtag.js the WordPress way, with wp_enqueue_script and the async strategy, so it doesn’t block the page. The configuration line is added right before it. Two checks keep things clean: nothing loads until a valid ID is set, and administrators aren’t tracked.

Where to find your Measurement ID

In Google Analytics go to Admin → Data streams, open your web stream and copy the ID that starts with G-. Paste it in the builder, under Measurement ID, before you copy the code.

Before you use it

This loads Analytics for every visitor, without asking. If your site has visitors from the EU, you need their consent first, so load the tag through your consent solution instead.

How to check it works

Open the site in a private window, without logging in. Within a minute your visit should appear in Reports → Realtime.

How to undo it

Remove the code. Tracking stops on the next page load.

How to add this snippet

  1. Copy the code above.
  2. Paste it at the end of your child theme’s functions.php, in Appearance → Theme File Editor or over FTP.
  3. Save, then open the site and check that everything works. If something breaks, remove the code.

Need more than one? Open this snippet in the builder, turn on the others you want and copy them as one functions.php, or download them as a small plugin.

More in SEO