How to add Google Analytics to a WordPress site

Cathy D Dec 16, 2024 Analytics
How do I see how many people visit my website?
What are the steps to integrate Google Analytics tracking code into my WordPress site for detailed visitor statistics?
Andy answered Dec 16, 2024

There are two main approaches to add Google Analytics to your WordPress site and track visitor statistics:

Method 1: Using Google Analytics Plugin (Recommended for Beginners)

The easiest way is to use a dedicated plugin. Here are the top options:

  1. MonsterInsights (website)

    • Most popular Analytics plugin
    • User-friendly dashboard inside WordPress
    • Free and premium versions available
    • Easy setup wizard
  2. GA Google Analytics (website)

    • Lightweight alternative
    • Simple setup
    • Free version works well for basic needs

Method 2: Manual Integration

For developers or those who prefer not to use plugins:

  1. Create a Google Analytics 4 property:

    • Go to Google Analytics
    • Set up a new property
    • Get your Measurement ID (starts with "G-")
  2. Add the tracking code in one of these ways:

    a. Via theme's header.php:

    • Add code right before the closing </head> tag
    • Remember this will be lost if you update your theme

    b. Via functions.php (recommended): Add this code to your child theme's functions.php:

function add_google_analytics() {
    ?>
    <!-- Google tag (gtag.js) -->
    <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 Measurement ID)

Best Practices & Security Tips:

  1. Use Google Analytics 4 (GA4) as Universal Analytics is being phased out
  2. Enable IP anonymization for GDPR compliance
  3. Add a cookie consent notice if you serve EU visitors
  4. Wait 24-48 hours after setup for data to appear
  5. Set up proper filters to exclude admin and developer IPs

Common Pitfalls:

  • Adding tracking code multiple times (via plugin and manually)
  • Not verifying the tracking code is working (use real-time reports)
  • Forgetting to verify site ownership in Google Search Console
  • Not setting up proper goals and conversions
  • Using outdated analytics code

Additional Plugin Options:

  • Site Kit by Google (website)

    • Official Google plugin
    • Integrates multiple Google services
    • Clean interface
    • Free to use
  • Analytify (website)

    • Beautiful dashboard
    • Real-time statistics
    • Free and premium versions

Once installed, allow 24-48 hours for data collection to begin. You can view your statistics either in your Google Analytics dashboard or through your chosen plugin's interface.