Installing Google Analytics 4 on WordPress | Blue Frog Docs

Installing Google Analytics 4 on WordPress

Complete guide to implementing GA4 on WordPress using plugins, manual integration, or GTM

Installing Google Analytics 4 on WordPress

This guide covers WordPress-specific methods for implementing Google Analytics 4 (GA4), from beginner-friendly plugins to developer-focused manual installation.

Prerequisites

Before installing GA4 on WordPress:

  1. Create a GA4 Property in Google Analytics

    • Sign in to analytics.google.com
    • Create a new GA4 property
    • Copy your Measurement ID (format: G-XXXXXXXXXX)
  2. Choose Your Implementation Method based on:

    • Technical expertise level
    • Performance requirements
    • Need for custom event tracking
    • Existing WordPress setup (theme, plugins, hosting)

Method 1: Google Site Kit (Official Plugin)

Best for: Beginners, standard tracking needs, multiple Google integrations

Why Site Kit?

  • Official WordPress plugin from Google
  • Connects GA4, Search Console, AdSense, PageSpeed Insights
  • No manual code editing
  • Automatic setup with OAuth authentication
  • Built-in dashboard in WordPress admin

Installation Steps

  1. Install the Plugin

    • Navigate to Plugins → Add New
    • Search for "Site Kit by Google"
    • Click Install NowActivate
  2. Connect to Google Account

    • Go to Site Kit → Dashboard
    • Click Start Setup
    • Authenticate with your Google account
    • Grant permissions to Site Kit
  3. Verify Site Ownership

    • Site Kit will verify ownership via Search Console
    • If not already verified, choose verification method:
      • HTML file upload (easiest for most users)
      • Meta tag (if you have header access)
      • Google Analytics (if already installed)
      • Google Tag Manager (if already using GTM)
  4. Set Up Analytics

    • Select Analytics from modules
    • Choose Create a new property or Use existing property
    • Select your GA4 property
    • Enable Enhanced Measurement (recommended)
    • Click Configure Analytics
  5. Verify Installation

    • Visit your website in a new browser window
    • Open Google Analytics Real-Time report
    • Confirm pageviews appear within 30 seconds

Site Kit Configuration

Enhanced Measurement

Automatically tracks:

  • Scrolls (90% depth)
  • Outbound clicks
  • Site search
  • Video engagement
  • File downloads

Events Setup

// Add to your child theme's functions.php to track custom events
add_action('wp_footer', 'custom_ga4_events');
function custom_ga4_events() {
    if (!function_exists('googlesitekit_analytics_get_tracking_id')) {
        return;
    }
    ?>
    <script>
        // Custom event example
        document.querySelectorAll('.cta-button').forEach(function(button) {
            button.addEventListener('click', function() {
                gtag('event', 'cta_click', {
                    'button_text': this.textContent,
                    'button_location': 'homepage'
                });
            });
        });
    </script>
    <?php
}

Site Kit Limitations

  • Limited customization options
  • Cannot control exact script placement
  • Requires Google account OAuth (some hosting environments block this)
  • Dashboard data may not match GA4 interface exactly

Method 2: Third-Party Analytics Plugins

Best for: Non-technical users needing more control than Site Kit

MonsterInsights (Freemium)

Most popular GA4 plugin with 3+ million active installations.

Features:

  • Universal Analytics to GA4 migration
  • Enhanced E-commerce tracking for WooCommerce
  • Form tracking (Contact Form 7, WPForms, Gravity Forms)
  • File download tracking
  • Affiliate link tracking
  • WordPress dashboard reports

Installation:

1. Install MonsterInsights from Plugins → Add New
2. Activate and click "Launch the Wizard"
3. Connect your Google account
4. Select your GA4 property
5. Configure tracking options:
   - Enhanced E-commerce (WooCommerce)
   - Events (downloads, outbound links)
   - Dimensions (authors, categories, tags)

Code Example - Custom Dimension:

// Add custom dimension to MonsterInsights
add_filter('monsterinsights_frontend_output_after_events', 'custom_mi_dimension');
function custom_mi_dimension($output) {
    if (is_user_logged_in()) {
        $user = wp_get_current_user();
        $output .= "gtag('set', 'user_properties', {'membership_level': '{$user->roles[0]}'});";
    }
    return $output;
}

ExactMetrics (Freemium)

Fork of MonsterInsights with similar features.

GA Google Analytics (Free)

Lightweight alternative with manual Measurement ID entry.

Installation:

1. Install "GA Google Analytics" plugin
2. Navigate to Settings → Google Analytics
3. Enter your Measurement ID (G-XXXXXXXXXX)
4. Select tracking options:
   - Track logged-in admins: No (recommended)
   - Anonymize IPs: Yes (for GDPR)
   - Enable demographics: Yes
5. Save changes

Plugin Performance Comparison

Plugin Page Weight HTTP Requests Database Queries
Site Kit ~150 KB +3 +5
MonsterInsights ~200 KB +4 +8
ExactMetrics ~200 KB +4 +8
GA Google Analytics ~50 KB +1 +1

Method 3: Manual Theme Integration

Best for: Developers, performance-critical sites, full control

Always use a child theme to prevent losing changes during theme updates.

1. Create Child Theme Structure:

/wp-content/themes/your-child-theme/
├── functions.php
├── style.css

2. style.css:

/*
Theme Name: Your Child Theme
Template: parent-theme-folder
Version: 1.0.0
*/

3. functions.php:

<?php
// Enqueue parent theme styles
add_action('wp_enqueue_scripts', 'child_theme_enqueue_styles');
function child_theme_enqueue_styles() {
    wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
}

// Add GA4 tracking code
add_action('wp_head', 'add_ga4_tracking', 1);
function add_ga4_tracking() {
    // Don't track admin users
    if (current_user_can('manage_options')) {
        return;
    }

    $measurement_id = 'G-XXXXXXXXXX'; // Replace with your ID
    ?>
    <!-- Google Analytics 4 -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo $measurement_id; ?>"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '<?php echo $measurement_id; ?>', {
            'anonymize_ip': true, // GDPR compliance
            'allow_google_signals': false, // Disable until consent
            'page_path': window.location.pathname
        });
    </script>
    <?php
}

Advanced Configuration

Exclude Logged-In Administrators

function add_ga4_tracking() {
    // Skip tracking for admins and editors
    if (current_user_can('edit_posts')) {
        return;
    }
    // ... tracking code
}
add_action('wp_head', 'add_ga4_with_consent', 1);
function add_ga4_with_consent() {
    ?>
    <!-- Google Analytics 4 with Consent Mode -->
    <script>
        // Set default consent (denied until user accepts)
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}

        gtag('consent', 'default', {
            'analytics_storage': 'denied',
            'ad_storage': 'denied',
            'wait_for_update': 500
        });

        gtag('js', new Date());
        gtag('config', 'G-XXXXXXXXXX');
    </script>
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>

    <!-- After user accepts cookies, update consent -->
    <script>
        document.addEventListener('cookie_consent_accepted', function() {
            gtag('consent', 'update', {
                'analytics_storage': 'granted'
            });
        });
    </script>
    <?php
}

Performance Optimization

// Preconnect to Google domains for faster loading
add_action('wp_head', 'ga4_preconnect', 1);
function ga4_preconnect() {
    echo '<link rel="preconnect" href="https://www.google-analytics.com">';
    echo '<link rel="preconnect" href="https://www.googletagmanager.com">';
}

// Delay GA4 loading until user interaction
add_action('wp_footer', 'delay_ga4_loading', 99);
function delay_ga4_loading() {
    ?>
    <script>
        // Delay GA4 until user interacts with page
        let gaLoaded = false;
        const loadGA = () => {
            if (gaLoaded) return;
            gaLoaded = true;

            const script = document.createElement('script');
            script.async = true;
            script.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX';
            document.head.appendChild(script);

            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-XXXXXXXXXX');
        };

        // Load on first user interaction
        ['mousedown', 'touchstart', 'keydown', 'scroll'].forEach(event => {
            window.addEventListener(event, loadGA, {once: true, passive: true});
        });

        // Fallback: load after 5 seconds
        setTimeout(loadGA, 5000);
    </script>
    <?php
}

Method 4: Google Tag Manager

Best for: Marketing teams, multiple tags, frequent changes

See the dedicated GTM Setup Guide for WordPress-specific GTM implementation.

Quick Setup:

  1. Install GTM container code in WordPress
  2. Add GA4 Configuration Tag in GTM
  3. Set up triggers (All Pages, custom events)
  4. Configure data layer variables

Benefits:

  • No WordPress edits needed for new tags
  • Version control and rollback
  • Built-in debugging (Preview mode)
  • Team collaboration features

WordPress-Specific Considerations

Caching Plugins

GA4 tracking works with most caching plugins, but verify:

// Exclude GA4 from caching (if issues occur)
// For WP Rocket:
add_filter('rocket_exclude_js', 'exclude_ga4_from_optimization');
function exclude_ga4_from_optimization($excluded_files) {
    $excluded_files[] = 'googletagmanager.com/gtag/js';
    $excluded_files[] = 'google-analytics.com/analytics.js';
    return $excluded_files;
}

// For W3 Total Cache: Go to Performance → Minify → Never minify → Add:
// googletagmanager.com/gtag/js

WooCommerce Integration

See GA4 E-commerce Tracking for WooCommerce-specific setup.

Multisite Networks

For WordPress Multisite, install GA4 network-wide:

// In wp-config.php or network-activated plugin
add_action('wp_head', 'multisite_ga4_tracking', 1);
function multisite_ga4_tracking() {
    $blog_id = get_current_blog_id();

    // Map blog IDs to Measurement IDs
    $ga4_ids = array(
        1 => 'G-MAIN-SITE',
        2 => 'G-BLOG-TWO',
        3 => 'G-BLOG-THREE'
    );

    $measurement_id = isset($ga4_ids[$blog_id]) ? $ga4_ids[$blog_id] : 'G-DEFAULT';

    // ... tracking code with $measurement_id
}

Page Builders (Elementor, Divi, Beaver Builder)

Most page builders are compatible with all GA4 installation methods:

  • Plugins work automatically
  • Manual theme integration works if child theme is properly configured
  • GTM requires proper data layer for dynamic content

Headless WordPress

For headless WordPress (REST API, GraphQL):

  • Install GA4 in the frontend framework (Next.js, Gatsby, React)
  • Use WordPress only for data layer values (post meta, user data)
  • Consider Measurement Protocol for server-side tracking

Validation and Testing

1. Real-Time Reports

  • Visit your website
  • Open Google Analytics → Reports → Realtime
  • Confirm pageview appears within 30 seconds

2. Browser DevTools

// Check if gtag is loaded (browser console)
console.log(window.gtag);
console.log(window.dataLayer);

// Manually fire test event
gtag('event', 'test_event', {'test_parameter': 'test_value'});

3. Google Analytics Debugger Extension

  • Install GA Debugger for Chrome
  • Enable the extension
  • Reload your site
  • Check console for GA4 hit details

4. Tag Assistant

  • Install Tag Assistant
  • Connect to your site
  • Verify GA4 tag fires correctly

Common Installation Issues

See Tracking Troubleshooting for debugging WordPress-specific problems.

Migration from Universal Analytics

If migrating from UA (analytics.js):

// Keep both UA and GA4 during transition period
add_action('wp_head', 'dual_tracking_ga', 1);
function dual_tracking_ga() {
    ?>
    <!-- Google Analytics 4 -->
    <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());

        // GA4 property
        gtag('config', 'G-XXXXXXXXXX');

        // Universal Analytics property (deprecated but running during transition)
        gtag('config', 'UA-XXXXXXXXX-X');
    </script>
    <?php
}

Migration Timeline:

  1. Month 1-2: Run UA and GA4 simultaneously
  2. Month 2-3: Compare data, adjust GA4 configuration
  3. Month 3-4: Shift reporting to GA4
  4. Month 4+: Remove UA code

Next Steps

// SYS.FOOTER