As the title suggests, I have no intention of tracking my admin activity on the page. The idea is to disable Google Analytics when the admin is logged in.
To simply disable Google Analytics, you just need to set the ‘ga-disable’ window variable to ‘true’.
I suppose this can be added anywhere on the page, but in my case, I’ve added the ‘disable’ attribute to the header tag.
true, effectively disabling Google Analytics tracking for that user’s session on the page. This can be useful to prevent administrators from skewing website analytics when they are logged in and working on the site.
<?php if (current_user_can('administrator')):?> <script> window['ga-disable-GA-IDENTIFICATOR'] = true; </script> <?php endif;?> <?php wp_head(); ?>
<?php if (current_user_can('administrator')):?>: This line is a conditional statement in PHP. It checks if the current user has the role of “administrator” in WordPress. If the user is an administrator, the code within the
ifblock will execute.
true. This variable is used to disable Google Analytics tracking for the current page.
window. This object is used to store variables that can be accessed throughout the web page.
'ga-disable-GA-IDENTIFICATOR'is the name of the variable being created. This name is used as a reference to disable Google Analytics.
trueis the value assigned to the variable, indicating that Google Analytics tracking should be disabled.
<?php endif; ?>: This line ends the conditional statement started with
if. If the current user is not an administrator, the code within the
ifblock is skipped.
<?php wp_head(); ?>: This line is a WordPress function call. It is typically included in the
<head>section of a WordPress theme and is used to output various scripts, stylesheets, and other elements that should be loaded in the
<head>of the HTML document. In this context, it’s used to ensure that the script defined above is included in the website’s HTML.