Adding Google Analytics Tracking Code in WordPress for Better Insights

Johan S Jan 9, 2025 Analytics
How can I check how many people visit my website?
What is the best method to add Google Analytics tracking code to a WordPress site for comprehensive visitor insights?
Andy answered Jan 9, 2025

Adding Google Analytics to WordPress

Custom Code Solution

This solution adds the Google Analytics 4 (GA4) tracking code to your WordPress site using the proper WordPress hooks.

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

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

To exclude tracking for admin users, use this enhanced version:

function add_google_analytics_with_exclusions() {
    // Don't track admin users
    if (current_user_can('manage_options')) {
        return;
    }
    
    $tracking_id = 'GA_MEASUREMENT_ID';
    ?>
    <!-- Google Analytics 4 tracking code -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr($tracking_id); ?>"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '<?php echo esc_attr($tracking_id); ?>');
    </script>
    <?php
}
add_action('wp_head', 'add_google_analytics_with_exclusions', 10);

Plugin Solutions

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

  1. MonsterInsights - Most popular analytics plugin

    • Easy setup wizard
    • Dashboard integration
    • E-commerce tracking
  2. GA Google Analytics - Lightweight option

    • Simple setup
    • Basic features
    • Free
  3. Google Site Kit - Official Google plugin

    • Multiple Google services integration
    • Direct Google authentication
    • Free

Important Notes

  1. Get your GA4 Measurement ID from Google Analytics:

    • Go to Admin → Property → Data Streams
    • Select your web stream
    • Copy the Measurement ID (starts with "G-")
  2. After adding the tracking code:

    • Wait 24-48 hours for data to appear
    • Use Google Analytics Real-Time reports to verify installation
    • Test in incognito mode if using admin exclusion
  3. Consider privacy laws:

    • Add cookie consent if needed
    • Update privacy policy
    • Enable IP anonymization if required