How to stop google analytics tracking logged in users in WordPress
- Date:
- 8 Sep 2010
- Category:
There are plenty of tutorials covering adding google analytics to your site, and preventing google from tracking signed in users. None seemed to offer the seemingly simple variation which I was searching for – don’t track signed in users and also don’t track me if I’m browsing the local version of my site while not logged in. Here’s how it’s done.
This tutorial assumes that you are familiar with using functions.php. The finished result is a function which looks to see if the you are logged in, fetches the server address and based upon those two pieces of information, decides whether or not to insert the google tracking code. First up, the basic function and the action to add it:
function add_googleanalytics() {
// put code here
}
add_action('wp_footer', 'add_googleanalytics');
Next the conditional stuff. Here two things are required, I’ve used $_SERVER['SERVER_NAME'] to find the name of the server and the WordPress function is_user_logged_in() to detect whether or not a user is logged in. Using get_bloginfo(‘url’) to fetch the server address would work just as well. The trick to getting is_user_logged_in() to function correctly is to ask if a user is NOT signed in. So, if user is not signed in and the server name is not my local server name do something, otherwise do something else. Here I’m echoing a note to check the code is functioning:
function add_googleanalytics() {
$ip = $_SERVER['SERVER_NAME'];
if (!is_user_logged_in()  &&  ($ip !== www.creativeglo.co.uk )) {
echo '<-- not logged in and server address IS NOT local ' . $ip . ' -->';
} else {
echo '<-- logged in or sever address IS local ' . $ip . ' -->';
}
}
add_action('wp_footer', 'add_googleanalytics');
Finally, a small alteration to allow the insertion of the tracking code
function add_googleanalytics() {
$ip = $_SERVER['SERVER_NAME'];
if (!is_user_logged_in()  &&  ($ip !== www.creativeglo.co.uk )) {
echo '<-- not logged in or server address IS NOT local ' . $ip . ' -->';
?>
<!-- tracking code goes here -->
<?php } else {
echo '<-- logged in or sever address IS local ' . $ip . ' -->';
}
}
add_action('wp_footer', 'add_googleanalytics');
Happy tracking.
Documentation on the sis_user_logged_in() function in the WordPress codex here, and php $_SERVER[] variables here.