Google Analytics 4 Without Tracking Logged-In Staff
Outputs the GA4 tag only for visitors and customers, so your own visits as an author, editor or administrator do not skew the statistics.
Opens WPIDE on
Code
add_action( 'wp_head', function () {
$measurement_id = 'G-XXXXXXXXXX'; // Your GA4 Measurement ID.
if ( current_user_can( 'edit_posts' ) || 'G-XXXXXXXXXX' === $measurement_id ) {
return;
}
printf(
"<script async src=\"%s\"></script>\n<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config',%s);</script>\n",
esc_url( 'https://www.googletagmanager.com/gtag/js?id=' . rawurlencode( $measurement_id ) ),
wp_json_encode( $measurement_id )
);
}, 5 );
Notes
Replace G-XXXXXXXXXX with your Measurement ID. Nothing is printed while the placeholder is still in place.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.