General WordPress

Adding Google Analytics Tracking Code

2 min read Updated Sep 2026 General WordPress

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

  1. Go to PluginsAdd Plugin, then install and activate Code Snippets.
  2. Go to SnippetsAdd New and name the snippet Google Analytics.
  3. Paste the code below. Replace both G-XXXXXXXXXX values with your Measurement ID.
  4. Set the scope to Only run on site front-end.
  5. Click Save and Activate.

The Google Analytics 4 snippet in the Code Snippets editor

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.

  1. Go to AppearanceEditor and open a template that has your header.
  2. Add a Custom HTML block to the header and paste the two Google script tags into it.
  3. Click Save.

The Google Analytics tag in a Custom HTML block in the header template part

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.