Solution 1: Custom Code Implementation
Add this code to your theme's functions.php
file or in a site-specific plugin:
This code adds the Google Analytics 4 tracking code to the head section of your site using the wp_head
hook:
function add_google_analytics() {
// Replace G-XXXXXXXXXX with your actual Google Analytics 4 Measurement ID
$ga_id = 'G-XXXXXXXXXX';
?>
<!-- Google Analytics 4 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr($ga_id); ?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<?php echo esc_attr($ga_id); ?>');
</script>
<?php
}
add_action('wp_head', 'add_google_analytics', 10);
For better performance, you can load Analytics asynchronously in the footer using wp_footer
:
function add_google_analytics_async() {
// Replace G-XXXXXXXXXX with your actual Google Analytics 4 Measurement ID
$ga_id = 'G-XXXXXXXXXX';
?>
<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.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr($ga_id); ?>','gtag');
gtag('js', new Date());
gtag('config', '<?php echo esc_attr($ga_id); ?>');
</script>
<?php
}
add_action('wp_footer', 'add_google_analytics_async', 10);
Solution 2: Plugin Options
If you prefer using a plugin, here are reliable options:
-
MonsterInsights - Most popular Analytics plugin with detailed reports in WordPress dashboard
-
GA Google Analytics - Lightweight plugin for basic Analytics integration
-
Site Kit by Google - Official Google plugin that includes Analytics and other Google services
Best Practices
- Always use your actual Google Analytics 4 Measurement ID
- Place custom code in a child theme or site-specific plugin
- Use
wp_enqueue_script()
for more complex tracking needs
- Consider implementing cookie consent if serving EU visitors
- Test tracking implementation using Google Analytics Real-Time reports
Remember to replace G-XXXXXXXXXX
with your actual Google Analytics 4 Measurement ID from your Google Analytics account.