Code Snippet to Add Google Analytics to WordPress

Marek T Jan 14, 2025 Analytics Integration
How do I track how many people visit my website using Google?
What is the recommended code snippet to integrate Google Analytics tracking code into the header of a WordPress site without using a plugin?
Andy answered Jan 15, 2025

Adding Google Analytics to WordPress Without a Plugin

Custom Code Solution

To add Google Analytics to your WordPress site, you'll need your Google Analytics tracking ID (starts with 'G-' for GA4 or 'UA-' for Universal Analytics).

Add this code to your theme's functions.php file or a site-specific plugin:

This code adds the Google Analytics 4 tracking code to your site's header:

function add_google_analytics() {
    ?>
    <!-- Google Analytics -->
    <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
}
add_action('wp_head', 'add_google_analytics');

Replace G-XXXXXXXXXX with your actual Google Analytics 4 tracking ID.

For Universal Analytics (older version), use this code instead:

function add_universal_analytics() {
    ?>
    <!-- Google Analytics (Universal) -->
    <script>
        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-XXXXXXXXX-X', 'auto');
        ga('send', 'pageview');
    </script>
    <?php
}
add_action('wp_head', 'add_universal_analytics');

Replace UA-XXXXXXXXX-X with your Universal Analytics tracking ID.

Plugin Solutions

If you prefer using a plugin, here are reliable options:

  1. MonsterInsights - Most popular analytics plugin
  2. GA Google Analytics - Lightweight option
  3. Site Kit by Google - Official Google plugin

Additional Notes

  • Use only one version of the tracking code (GA4 or Universal Analytics)
  • Place the code before the closing </head> tag
  • The wp_head hook ensures proper placement
  • Consider using a child theme when modifying functions.php
  • For local development, consider conditionally loading the tracking code only on production