How to Disable Google Analytics in Preview Mode in WordPress

Home » Snippets » How to Disable Google Analytics in Preview Mode in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you tired of seeing your own visits being counted in Google Analytics while previewing your website? It can be frustrating to have your own browsing habits skew your website’s analytics data. Fortunately, there is a way to disable Google Analytics in preview mode, ensuring that your own visits are not tracked. In this article, we will show you how to easily disable Google Analytics in preview mode and keep your data accurate.

					function wpturbo_disable_google_analytics_preview() {
    if ( is_admin_preview() ) {
        add_filter( 'wp_footer', function() {
            echo '<script>gaOptout=true;</script>';
        });
    }
}
add_action( 'wp', 'wpturbo_disable_google_analytics_preview' );
				

The code snippet provided above demonstrates how to disable Google Analytics in preview mode on a WordPress website.

To begin, we create a function called wpturbo_disable_google_analytics_preview() using the function keyword in PHP. This function will be responsible for disabling Google Analytics when the website is in preview mode.

Inside this function, we use an if statement to check if the current page is in the WordPress admin preview. We achieve this by using the is_admin_preview() function, which returns true if the current page is being previewed in the WordPress admin.

If the page is in preview mode, we proceed to add a filter using the add_filter() function. This filter will modify the output of the wp_footer hook, which is a common hook used for injecting code into the footer of a WordPress website.

We define a new anonymous function inside the add_filter() function, which will be called when the wp_footer hook is triggered. Inside this anonymous function, we output a script tag containing a JavaScript code snippet. This JavaScript code, <script>gaOptout=true;</script>, sets the gaOptout variable to true. This variable is used by the Google Analytics script to disable tracking.

Finally, we hook the wpturbo_disable_google_analytics_preview() function into the wp action using the add_action() function. The wp action is triggered after WordPress has finished loading but before any output is sent to the browser. By hooking into this action, our function is executed at the appropriate time to disable Google Analytics in preview mode.

In summary, the code snippet checks if the current page is in preview mode, and if so, injects a JavaScript code snippet into the footer of the website that sets a variable to disable Google Analytics tracking.

Register an account to save your snippets or go Pro to get more features.