← All posts

No analytics for logged users

· WordPress, Analytics

First appeared on mobifreaks.com · Updated

Every time you open your own site to write or check something, you show up in your analytics. In 2011 I fixed that on Mobifreaks by only serving the Google Analytics code to visitors who were not logged in, so admins, editors and contributors didn't count.

The 2011 version

I wrapped the old ga.js snippet in a shortcode, registered it only for logged-out visitors, and called it from the theme with do_shortcode():

function google_analytics() {
    return "<script>/* the ga.js snippet, with _setAccount and _trackPageview */</script>";
}
if ( ! is_user_logged_in() ) {
    add_shortcode( 'ga', 'google_analytics' );
}

It worked, but it was clumsy, and the code inside it is gone: Google retired ga.js, and then Universal Analytics stopped processing data in July 2023. Google Analytics 4 is the current version.

The same idea today

No shortcode needed. Hook into wp_head and print the tag only when nobody is logged in:

<?php
add_action( 'wp_head', function () {
    if ( is_user_logged_in() ) {
        return;
    }
    $id = 'G-XXXXXXXXXX'; // your GA4 measurement ID
    ?>
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr( $id ); ?>"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){ dataLayer.push(arguments); }
      gtag('js', new Date());
      gtag('config', '<?php echo esc_js( $id ); ?>');
    </script>
    <?php
} );
  • is_user_logged_in() still does the job: it returns true for anyone signed in to the dashboard.
  • Put it in a small plugin or your theme's functions.php.
  • If you use Google Site Kit or another analytics plugin, check its settings first; most have an option to exclude logged-in users.

Two more things worth doing

  • Filter internal traffic. GA4 can also exclude visits by IP address under Admin → Data streams → Configure tag settings → Define internal traffic, which covers visits when you are logged out.
  • Check consent rules. If you have visitors from the EU or UK, you may need a consent banner before loading analytics at all.