How to Add Google Analytics to WordPress

How to add Google Analytics to WordPress

Google Analytics tracks your site’s traffic, user behaviour and conversions. There are two ways to add it to WordPress: a plugin, or the tracking snippet added from functions.php. The code way takes a few lines and gives you full control.

Problem: How do you add the Google Analytics tracking code to every page of a WordPress site without editing every template file?

Solution: Print the tracking snippet on the wp_head hook from functions.php (or from a small site-specific plugin, so it survives a theme change).

Method 1: add the snippet in functions.php

add_action( 'wp_head', 'add_google_analytics' );
function add_google_analytics() {
    // Don't track logged-in administrators.
    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 tracking ID from Google Analytics → Admin → Property → Tracking Info.

Skipping administrators keeps your data clean: your own visits while testing or writing posts don’t inflate the numbers. If several people manage the site, also add a filter in Google Analytics that excludes your office IP address.

Method 2: a plugin

MonsterInsights is the most popular option. It adds the snippet automatically and shows a stats dashboard inside WordPress. It is the easier choice if non-technical people need to see the reports without logging in to Google Analytics.

Track events

To track actions such as form submissions, button clicks or downloads alongside page views, send custom events with gtag():

// Track a contact form submission
var form = document.querySelector( '#contact-form' );

if ( form ) {
    form.addEventListener( 'submit', function() {
        gtag( 'event', 'form_submit', {
            'event_category': 'Contact',
            'event_label': 'Contact Page Form'
        } );
    } );
}

Update: Universal Analytics (IDs starting with UA-) stopped collecting data in July 2023. The snippet for Google Analytics 4 is the same gtag.js code; only the measurement ID starts with G-, and events use GA4 parameters instead of event_category and event_label.