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:
-
MonsterInsights - Most popular analytics plugin
- Easy setup wizard
- Dashboard integration
- E-commerce tracking
-
GA Google Analytics - Lightweight option
- Simple setup
- Basic features
- Free
-
Google Site Kit - Official Google plugin
- Multiple Google services integration
- Direct Google authentication
- Free
Important Notes
-
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-")
-
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
-
Consider privacy laws:
- Add cookie consent if needed
- Update privacy policy
- Enable IP anonymization if required