Add Google Analytics Tracking Code to WordPress

Lukas T. Jan 2, 2025 Analytics
How can I add Google Analytics to my website so I can see how many people visit it?
What is the best method to programmatically insert the Google Analytics tracking code into the header of a WordPress theme without modifying core files?
Andy answered Jan 2, 2025

Solution 1: Custom Code Implementation

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

This code adds the Google Analytics 4 tracking code to the head section of your site using the wp_head hook:

function add_google_analytics() {
    // Replace G-XXXXXXXXXX with your actual Google Analytics 4 Measurement ID
    $ga_id = 'G-XXXXXXXXXX';
    ?>
    <!-- Google Analytics 4 -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr($ga_id); ?>"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '<?php echo esc_attr($ga_id); ?>');
    </script>
    <?php
}
add_action('wp_head', 'add_google_analytics', 10);

For better performance, you can load Analytics asynchronously in the footer using wp_footer:

function add_google_analytics_async() {
    // Replace G-XXXXXXXXXX with your actual Google Analytics 4 Measurement ID
    $ga_id = 'G-XXXXXXXXXX';
    ?>
    <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.googletagmanager.com/gtag/js?id=<?php echo esc_attr($ga_id); ?>','gtag');
        gtag('js', new Date());
        gtag('config', '<?php echo esc_attr($ga_id); ?>');
    </script>
    <?php
}
add_action('wp_footer', 'add_google_analytics_async', 10);

Solution 2: Plugin Options

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

  1. MonsterInsights - Most popular Analytics plugin with detailed reports in WordPress dashboard
  2. GA Google Analytics - Lightweight plugin for basic Analytics integration
  3. Site Kit by Google - Official Google plugin that includes Analytics and other Google services

Best Practices

  1. Always use your actual Google Analytics 4 Measurement ID
  2. Place custom code in a child theme or site-specific plugin
  3. Use wp_enqueue_script() for more complex tracking needs
  4. Consider implementing cookie consent if serving EU visitors
  5. Test tracking implementation using Google Analytics Real-Time reports

Remember to replace G-XXXXXXXXXX with your actual Google Analytics 4 Measurement ID from your Google Analytics account.