Google Analytics tracks your site’s traffic, user behaviour, and conversion goals. There are two ways to add it to WordPress: using a plugin (recommended for most users) or adding the tracking snippet directly in functions.php. As of 2019 Google Analytics uses Universal Analytics (analytics.js); the newer GA4 was not yet available.
Problem: How do you add the Google Analytics tracking script to every page of a WordPress site without editing every template file or relying on a heavyweight plugin?
Solution: Output the gtag.js snippet via wp_head in functions.php, or use wp_enqueue_script() for the library and wp_add_inline_script() for the config call — keeping tracking code in the theme or a site-specific mu-plugin rather than the page templates.
Method 1 — via functions.php (no plugin needed, full control):
add_action( 'wp_head', 'add_google_analytics' );
function add_google_analytics() {
// Don't track admin users
if ( current_user_can( 'manage_options' ) ) {
return;
}
?>
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXX-Y"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push( arguments ); }
gtag( 'js', new Date() );
gtag( 'config', 'UA-XXXXX-Y' );
</script>
<?php
}
Replace UA-XXXXX-Y with your actual tracking ID from Google Analytics → Admin → Property → Tracking Info.
Method 2 — via a plugin. MonsterInsights and Site Kit by Google are the most popular options. They add the snippet automatically and provide a stats dashboard inside WordPress.
If you want to track events (button clicks, form submissions, downloads) alongside page views, fire custom events with gtag():
// Track a contact form submission
document.querySelector( '#contact-form' ).addEventListener( 'submit', function() {
gtag( 'event', 'form_submit', {
'event_category': 'Contact',
'event_label': 'Contact Page Form',
} );
} );
NOTE: Skipping admin-user tracking (as shown in the current_user_can check above) keeps your analytics data clean — your own visits while testing or writing posts won't inflate the numbers. If multiple people manage the site, set up a filter in Google Analytics to exclude your office IP address as well.