Google Analytics is a very popular statistics service. In order to get your traffic information, it provides you with a tracking code, which needs to be added to all the pages of your site.
How to add the tracking code
- Log into your Google Analytics account, and copy your tracking code.
- In your WordPress Dashboard, go to NiceThemes → Theme Options.
- In the theme options panel, go to General Settings.
- Paste your tracking code into the Tracking Code option.
- Click the Save Changes button at the top.
How to conditionally print the tracking code
There is a chance that you may not always want to track all the activity of your site. In example, let’s say you only give user accounts to editors or administrators. In that case, you should only track the activity of unlogged, because doing otherwise may alter your statistics and lead to inaccurate information. All that such a requirement would take is a little bit of code in your functions.php
file:
if ( ! function_exists( 'conditionally_do_tracking_code' ) ) : /** * Don't show tracking code for logged in users. * * @return bool */ function conditionally_do_tracking_code() { if ( is_user_logged_in() ) { return false; } return true; } endif;
The function must return a boolean value, which should be true
for every case in which you want to show the tracking code, and false
for every case in which you want to hide it. In the example, we use the WordPress function is_user_logged_in()
, which returns true
if a user is currently logged in, and false
if not.
As you can see, it’s very easy to customize this function to suit other needs. The only thing you need to remember is to always return a boolean value.