Google Analytics is one of the most important tools for tracking website traffic, user behavior, and conversions. To ensure the tracking script loads properly across your WordPress website, it is recommended to add the Google Analytics code inside the <head> tag.
Instead of editing the header.php file directly, you can use a WordPress hook to safely insert the tracking code. This method follows WordPress best practices and keeps your customizations easier to manage.
By default, WordPress does not provide a dedicated setting for adding custom scripts to the head section without a plugin, but it can be easily done using a simple PHP snippet.
Snippet: Add Google Analytics Code in Head Tag Using WordPress Hook
Use the following snippet to add your Google Analytics tracking code inside the <head> section of your WordPress website:
// Add Google Analytics Code in WordPress Head Tag
add_action( 'wp_head', 'shez_add_google_analytics_code' );
function shez_add_google_analytics_code() {
?>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX');
</script>
<?php
}Replace the Tracking ID
Replace G-XXXXXXXXXX in the code with your actual Google Analytics Measurement ID. You can find this ID in your Google Analytics account under the Data Streams settings. The Measurement ID usually starts with G- followed by a combination of letters and numbers, for example: G-ABCD123456.
Where to add this custom code?
Add this code to your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Code snippets plugin.
About Sheraz Ghani
Hey, I’m Sheraz, a WordPress developer who codes every day, and I share what I learn so other developers don’t have to figure it out the hard way.
Shez.dev is where I document useful WordPress code snippets, troubleshooting guides and developer tutorials.
Need some developer help? Contact me