Google Analytics condition seems off

See https://github.com/roots/roots/blob/master/lib/scripts.php#L102

I thought the purpose of the Google Analytics condition was to only use the tracking code when:

  • Tracking code exists
  • In production
  • Not a logged in admin

However, the condition seems to return true when not in production. Is this the intention, am I missing something? I have double checked the constants are correct and I’m getting analytics events firing in console in my dev version. Here’s a test:

if (GOOGLE_ANALYTICS_ID && (WP_ENV !== 'production' || !current_user_can('manage_options')))

Sub in actual values for logged in admin in development:

if ( 'UA-XXXXX-Y' && ( 'development' !== 'production' || ! true ) )

if ( true && ( true || false ) )

So the condition will return true for those values and load tracking.
Let’s try in production and not admin…

if ( UA-XXXXX-Y && ( 'production' !== 'production' || ! false ) )

if ( true && ( false || true ) )

Yep works fine there, but only because its not an admin.

I feel like I must be missing something because surely someone would have noticed this already? Unless the point is to use a tracking code in roots specifically for development analytics and use a different code with a plugin or something for production analytics?

Otherwise shouldn’t the check be WP_ENV == 'production', not !== and check that BOTH the env is production AND the user is not admin:

if (GOOGLE_ANALYTICS_ID && WP_ENV == 'production' && !current_user_can('manage_options') )

Am I crazy?

You’ll find some discussion at roots/roots #1232 (or older: #1188).

1 Like

Thanks, I looked for existing topics but didn’t find those. #1188 explained the logic.

It all makes sense now. I didn’t read the ‘roots_google_analytics’ function carefully enough.

2 Likes

Gonna rewrite this condition for 8.0.0. Added as a task on https://github.com/roots/roots/pull/1251 - pull requests welcome :blush:

/cc @swalkinshaw @QWp6t