To add Google Analytics tracking code to WordPress, load the Google tag on every front-end page. Use a plugin such as Site Kit by Google, or add the tag with code as shown here.
Find the Measurement ID
Google Analytics 4 uses a Measurement ID that starts with G-. Google explains where to find it. The old UA- codes no longer work.
Code Snippets Plugin
- Go to PluginsAdd Plugin, then install and activate Code Snippets.
- Go to SnippetsAdd New and name the snippet Google Analytics.
- Paste the code below. Replace both
G-XXXXXXXXXXvalues with your Measurement ID. - Set the scope to Only run on site front-end.
- Click Save and Activate.

add_action( 'wp_enqueue_scripts', 'puro_google_analytics_tag' );
function puro_google_analytics_tag() {
wp_enqueue_script(
'puro-gtag',
'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX',
array(),
null,
array( 'strategy' => 'async' )
);
wp_add_inline_script(
'puro-gtag',
"window.dataLayer = window.dataLayer || [];\nfunction gtag(){dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', 'G-XXXXXXXXXX');",
'before'
);
}Replace puro_google_analytics_tag with your own function name in both places it appears. The same code works in the functions.php file of a child theme.
Block Themes
The plugin route above works in a block theme. You can also add the tag as a block in the header.
- Go to AppearanceEditor and open a template that has your header.
- Add a Custom HTML block to the header and paste the two Google script tags into it.
- Click Save.

WordPress removes script tags from a Custom HTML block when the user lacks the
unfiltered_html capability. Save the block as a user with that capability. Administrators have it on a single site. On multisite, a Super Admin has it.Related
Was this helpful?