Adding Google Analytics to WordPress
Custom Code Solution
Add this code to your theme's functions.php
file or a site-specific plugin. It inserts the Google Analytics 4 tracking code in the <head>
section of your website:
function add_google_analytics() {
// Replace GA_MEASUREMENT_ID with your actual Google Analytics 4 tracking ID
$tracking_id = 'GA_MEASUREMENT_ID';
?>
<!-- Google Analytics 4 tag -->
<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);
Alternative Solution (Universal Analytics)
If you're still using the older Universal Analytics (UA), use this code instead:
function add_universal_analytics() {
// Replace UA-XXXXX-Y with your actual Universal Analytics tracking ID
$tracking_id = 'UA-XXXXX-Y';
?>
<!-- Universal Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '<?php echo esc_attr($tracking_id); ?>', 'auto');
ga('send', 'pageview');
</script>
<?php
}
add_action('wp_head', 'add_universal_analytics', 10);
Plugin Solutions
If you prefer using a plugin, here are reliable options:
-
MonsterInsights - Most popular Google Analytics plugin
-
Google Site Kit - Official Google plugin for WordPress
-
GA Google Analytics - Lightweight alternative
Best Practices
- Always replace the tracking ID placeholder with your actual Google Analytics ID
- Test tracking implementation using Google Analytics Real-Time reports
- Consider using a child theme when modifying
functions.php
- For production sites, minify the JavaScript code
- Consider implementing privacy-related features (like IP anonymization) if needed for GDPR compliance
Remember to get your tracking ID from your Google Analytics account and replace the placeholder in the code before implementation.