WordPress Google Analytics Integration | Blue Frog Docs

WordPress Google Analytics Integration

Integrate Google Analytics 4 with WordPress for comprehensive analytics tracking.

WordPress Google Analytics Integration

Complete guide to setting up Google Analytics 4 (GA4) on your WordPress site for comprehensive user behavior and conversion tracking.

Overview

WordPress is the world's most popular content management system, powering over 40% of websites. GA4 integration with WordPress can be accomplished through plugins, manual code insertion, or theme functions. The platform's extensive plugin ecosystem makes it easy to implement sophisticated tracking without writing code, while also offering flexibility for developers who need custom implementations.

Key Benefits

  • Plugin Ecosystem: Hundreds of GA4 plugins available for easy installation
  • WooCommerce Integration: Deep ecommerce tracking for WooCommerce stores
  • Custom Post Types: Track custom content types and taxonomies
  • User Role Tracking: Segment data by WordPress user roles
  • Membership Integration: Track member-only content and subscriptions
  • Site Kit by Google: Official Google plugin with GA4 integration
  • MonsterInsights: Premium plugin with advanced features
  • GA Google Analytics: Lightweight free plugin
  • ExactMetrics: User-friendly analytics plugin
  • Insert Headers and Footers: Simple code injection

Installation Methods

Official Google plugin for WordPress with native GA4 support.

Step 1: Install Site Kit

  1. Log in to WordPress admin
  2. Navigate to Plugins > Add New
  3. Search for "Site Kit by Google"
  4. Click Install Now, then Activate

Step 2: Connect Google Account

  1. Go to Site Kit in WordPress admin
  2. Click Start Setup
  3. Sign in with your Google account
  4. Grant Site Kit necessary permissions
  5. Verify site ownership

Step 3: Configure Analytics

  1. In Site Kit setup, select Analytics
  2. Choose Use existing property or Create new property
  3. Select your GA4 property
  4. Complete setup wizard
  5. Click Go to Dashboard

Method 2: MonsterInsights Plugin

Premium plugin with advanced tracking features.

Step 1: Install MonsterInsights

  1. Go to Plugins > Add New
  2. Search for "MonsterInsights"
  3. Install and activate the plugin
  4. For Pro features, upload premium version

Step 2: Connect GA4

  1. Navigate to Insights > Settings
  2. Click Authenticate with Google
  3. Select your Google account
  4. Choose GA4 property
  5. Complete authentication

Step 3: Configure Tracking

  1. Go to Insights > Settings > Engagement
  2. Enable desired tracking:
    • Scroll tracking
    • Outbound links
    • File downloads
    • Affiliate links
  3. For WooCommerce: Insights > eCommerce
  4. Enable enhanced ecommerce tracking
  5. Save changes

Method 3: Manual Code Installation

For complete control without plugins.

Add to Theme Functions

Add to your theme's functions.php:

function add_ga4_tracking() {
    ?>
    <!-- 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', {
        'send_page_view': true,
        'cookie_flags': 'SameSite=None;Secure'
      });
    </script>
    <?php
}
add_action('wp_head', 'add_ga4_tracking');

Using Insert Headers and Footers Plugin

  1. Install "Insert Headers and Footers" plugin
  2. Go to Settings > Insert Headers and Footers
  3. Paste GA4 code in Scripts in Header section
  4. Click Save

WooCommerce Ecommerce Tracking

Using MonsterInsights with WooCommerce

MonsterInsights automatically tracks WooCommerce events:

  1. Install MonsterInsights Pro
  2. Ensure WooCommerce is active
  3. Go to Insights > eCommerce
  4. Enable Use Enhanced Ecommerce
  5. Configure tracking options:
    • Product impressions
    • Product clicks
    • Add to cart
    • Remove from cart
    • Checkout steps
    • Purchases
  6. Save settings

Manual WooCommerce Tracking

Add custom tracking code to theme.

Product View Tracking

Add to functions.php:

add_action('woocommerce_after_single_product', 'ga4_track_product_view');

function ga4_track_product_view() {
    global $product;
    ?>
    <script>
        gtag('event', 'view_item', {
            'currency': '<?php echo get_woocommerce_currency(); ?>',
            'value': <?php echo $product->get_price(); ?>,
            'items': [{
                'item_id': '<?php echo $product->get_sku(); ?>',
                'item_name': '<?php echo esc_js($product->get_name()); ?>',
                'item_category': '<?php echo esc_js(strip_tags($product->get_categories())); ?>',
                'price': <?php echo $product->get_price(); ?>
            }]
        });
    </script>
    <?php
}

Add to Cart Tracking

add_action('woocommerce_after_add_to_cart_button', 'ga4_track_add_to_cart');

function ga4_track_add_to_cart() {
    global $product;
    ?>
    <script>
        jQuery(document).ready(function($) {
            $('button.single_add_to_cart_button').on('click', function() {
                gtag('event', 'add_to_cart', {
                    'currency': '<?php echo get_woocommerce_currency(); ?>',
                    'value': <?php echo $product->get_price(); ?>,
                    'items': [{
                        'item_id': '<?php echo $product->get_sku(); ?>',
                        'item_name': '<?php echo esc_js($product->get_name()); ?>',
                        'price': <?php echo $product->get_price(); ?>,
                        'quantity': $('.qty').val()
                    }]
                });
            });
        });
    </script>
    <?php
}

Purchase Tracking

Add to functions.php:

add_action('woocommerce_thankyou', 'ga4_track_purchase');

function ga4_track_purchase($order_id) {
    if (!$order_id) return;

    $order = wc_get_order($order_id);

    if (!$order) return;

    // Prevent duplicate tracking
    if ($order->get_meta('_ga4_tracked')) return;

    $items = array();
    foreach ($order->get_items() as $item) {
        $product = $item->get_product();
        $items[] = array(
            'item_id' => $product->get_sku(),
            'item_name' => $item->get_name(),
            'price' => $item->get_total() / $item->get_quantity(),
            'quantity' => $item->get_quantity()
        );
    }
    ?>
    <script>
        gtag('event', 'purchase', {
            'transaction_id': '<?php echo $order->get_order_number(); ?>',
            'value': <?php echo $order->get_total(); ?>,
            'tax': <?php echo $order->get_total_tax(); ?>,
            'shipping': <?php echo $order->get_shipping_total(); ?>,
            'currency': '<?php echo $order->get_currency(); ?>',
            'items': <?php echo json_encode($items); ?>
        });
    </script>
    <?php

    // Mark as tracked
    $order->update_meta_data('_ga4_tracked', 'yes');
    $order->save();
}

Advanced Event Tracking

Form Submission Tracking

Track Contact Form 7 submissions:

add_action('wpcf7_submit', 'ga4_track_cf7_submission', 10, 2);

function ga4_track_cf7_submission($contact_form, $result) {
    if ($result['status'] == 'mail_sent') {
        ?>
        <script>
            gtag('event', 'form_submit', {
                'form_name': '<?php echo $contact_form->title(); ?>',
                'form_id': <?php echo $contact_form->id(); ?>
            });
        </script>
        <?php
    }
}

Button Click Tracking

Track custom button clicks:

jQuery(document).ready(function($) {
    $('.cta-button').on('click', function() {
        gtag('event', 'cta_click', {
            'button_text': $(this).text(),
            'button_url': $(this).attr('href'),
            'page_location': window.location.href
        });
    });
});

Download Tracking

Track file downloads:

jQuery(document).ready(function($) {
    $('a[href$=".pdf"], a[href$=".zip"], a[href$=".doc"], a[href$=".docx"]').on('click', function() {
        var fileUrl = $(this).attr('href');
        var fileName = fileUrl.split('/').pop();

        gtag('event', 'file_download', {
            'file_name': fileName,
            'file_url': fileUrl,
            'link_text': $(this).text()
        });
    });
});

Scroll Depth Tracking

Monitor content engagement:

var scrollDepths = {25: false, 50: false, 75: false, 100: false};

jQuery(window).on('scroll', function() {
    var scrolled = (jQuery(window).scrollTop() / (jQuery(document).height() - jQuery(window).height())) * 100;

    Object.keys(scrollDepths).forEach(function(depth) {
        if (scrolled >= depth && !scrollDepths[depth]) {
            gtag('event', 'scroll', {
                'percent_scrolled': depth,
                'page_title': document.title
            });
            scrollDepths[depth] = true;
        }
    });
});

User and Role Tracking

Track Logged-In Users

add_action('wp_head', 'ga4_track_user_data');

function ga4_track_user_data() {
    if (is_user_logged_in()) {
        $current_user = wp_get_current_user();
        ?>
        <script>
            gtag('set', 'user_properties', {
                'user_role': '<?php echo $current_user->roles[0]; ?>',
                'user_status': 'logged_in'
            });

            gtag('config', 'G-XXXXXXXXXX', {
                'user_id': '<?php echo $current_user->ID; ?>'
            });
        </script>
        <?php
    }
}

Exclude Admin Users

Prevent tracking of admin users:

function add_ga4_tracking() {
    // Don't track logged-in administrators
    if (current_user_can('administrator')) {
        return;
    }

    ?>
    <!-- GA4 tracking code here -->
    <?php
}
add_action('wp_head', 'add_ga4_tracking');

Membership and Subscription Tracking

MemberPress Integration

Track membership signups:

add_action('mepr-event-transaction-completed', 'ga4_track_membership_purchase');

function ga4_track_membership_purchase($event) {
    $transaction = $event->get_data();
    ?>
    <script>
        gtag('event', 'purchase', {
            'transaction_id': '<?php echo $transaction->id; ?>',
            'value': <?php echo $transaction->total; ?>,
            'currency': 'USD',
            'items': [{
                'item_id': '<?php echo $transaction->product_id; ?>',
                'item_name': 'Membership',
                'item_category': 'Subscription',
                'price': <?php echo $transaction->total; ?>
            }]
        });
    </script>
    <?php
}

Privacy and GDPR Compliance

Work with cookie consent plugins:

function add_ga4_with_consent() {
    ?>
    <script>
        // Set default consent
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}

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

        // Update when user consents
        function acceptAnalytics() {
            gtag('consent', 'update', {
                'analytics_storage': 'granted'
            });
        }
    </script>

    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
    <script>
        gtag('js', new Date());
        gtag('config', 'G-XXXXXXXXXX');
    </script>
    <?php
}
add_action('wp_head', 'add_ga4_with_consent');

Troubleshooting

Tracking Not Working

Issue: No data appearing in GA4

Solutions:

  1. Clear WordPress cache (if using caching plugin)
  2. Check for JavaScript errors in browser console
  3. Verify Measurement ID is correct
  4. Disable other analytics plugins temporarily
  5. Check if ad blockers are interfering
  6. Test in incognito mode
  7. Verify plugin is properly configured

Duplicate Tracking

Issue: Events tracked multiple times

Solutions:

  1. Check for multiple GA4 implementations (plugin + manual)
  2. Verify tracking code isn't in both theme and plugin
  3. Check child theme and parent theme for duplicate code
  4. Review active plugins for conflicts
  5. Temporarily disable plugins to identify culprit

WooCommerce Events Not Firing

Issue: Ecommerce tracking not working

Solutions:

  1. Ensure WooCommerce and analytics plugin are compatible versions
  2. Clear all caches (WordPress, browser, CDN)
  3. Check if AJAX cart is preventing tracking
  4. Verify enhanced ecommerce is enabled in plugin settings
  5. Test with default WooCommerce theme
  6. Check for JavaScript conflicts with other plugins

Plugin Conflicts

Issue: Analytics plugin conflicts with other plugins

Solutions:

  1. Update all plugins to latest versions
  2. Test with default WordPress theme (Twenty Twenty-Three)
  3. Disable plugins one by one to identify conflict
  4. Check plugin support forums for known issues
  5. Contact plugin developer for assistance
  6. Consider switching to different analytics plugin

Performance Issues

Issue: Site slow after adding GA4

Solutions:

  1. Use async loading for gtag.js script
  2. Enable caching plugin (WP Rocket, W3 Total Cache)
  3. Consider using Google Tag Manager instead
  4. Defer non-critical JavaScript
  5. Use CDN for faster script delivery
  6. Minimize custom event tracking on page load

User Exclusion Not Working

Issue: Admin users still being tracked

Solutions:

  1. Clear browser cookies
  2. Verify exclusion code is before tracking code
  3. Check if caching is serving old version
  4. Test with different admin user
  5. Use incognito mode to test
  6. Check plugin settings for user exclusion options

Testing and Verification

Enable Debug Mode

Add to functions.php:

function ga4_debug_mode() {
    ?>
    <script>
        gtag('config', 'G-XXXXXXXXXX', {
            'debug_mode': true
        });
    </script>
    <?php
}
add_action('wp_head', 'ga4_debug_mode', 20);

Testing Checklist

  1. Page Views: Navigate site and verify in Real-time reports
  2. Ecommerce: Complete test WooCommerce purchase
  3. Forms: Submit contact forms
  4. Downloads: Click downloadable files
  5. User Roles: Test with different user roles
  6. Mobile: Test on mobile devices

WP-CLI Testing

Use WP-CLI for debugging:

# Check active plugins
wp plugin list --status=active

# Clear all caches
wp cache flush

# Check theme
wp theme list

Best Practices

Use Child Theme

Always add custom code to child theme to preserve changes during updates.

Regular Updates

Keep WordPress, themes, and plugins updated for security and compatibility.

Backup Before Changes

Create backup before modifying tracking code or installing new plugins.

Monitor Performance

Use tools like Query Monitor to track performance impact of tracking code.

Test Staging First

Test GA4 changes on staging site before deploying to production.

// SYS.FOOTER