Google Analytics
Most commonly used method of implementing Google Analytics to a site is by adding the global site tag, otherwise known as gtag.js
.
Global site tag should be placed immediately after the <head>
tag of every page, the wp_head
action with a high priority is a good action to do that for WordPress:
/**
* Google Analytics.
*/
add_action('wp_head', function() {
if(is_user_logged_in()) {
return;
}
?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
</script>
<?php
}, 5);
The 2 instances of GA_MEASUREMENT_ID
should be replaced with your Google Analytics property ID that looks something like this: UA-123123-3
.
The wp_head
action is executed on every page (but not admin dashboard) so this one snippet ensures all your posts and pages are tracked.
The snippet includes a condition if(is_user_logged_in()) { return; }
– this prevents logged in users from being tracked. In most cases this is just you, the site administrator. In case you have many users on the site and would like to track their pageviews, then this block can be removed.
If you’re looking to implement Universal Analytics (analytics.js
) then it can be implemented in a similar manner, but you’re most likely looking at something outdated, because it’s over 7 years old and gtag.js
has effectively replaced it.
Same goes for Google Tag Manager (gtm.js
), the gtag.js
is a newer solution that can probably get the job done.