WordPress: load PiWik statistics tracker script only for guests

Counting website visits with the open source tool PiWik is becoming more and more popular. PiWik is easy to install, easy to integrate with WordPress, Drupal, or any other CMS. The data reports can be self-hosted so they are all yours – and it’s free. The only thing about PiWik (and other website statistics tools) that used to annoy me was that I never knew if I really had that many visitors, or if it was just me. Of course: PiWik has an option to set a cookie “it’s me” so that your own visits would be ignored – and that is a good workaround if you happen to run your website on a self-coded basis that is not aware that it’s you, because it lacks of a login or the like…

With WordPress you actually have a system that can be aware at least if the visitor is currently logged in, or not. And there is quite a number of free Plugins that distinguish between ‘you’ and ‘the others’ by checking if the visitor is logged in, so only visits of real visitors (guests) are counted, but not visits of editors and administrator. That is of course great, but in most cases I just want to implement PiWik – and that’s it. So I usually just copy-paste the PiWik code snippet into the footer of the WordPress theme and all is fine.

Just placing the PiWik tracking code in the footer.php of your WordPress theme would then again make PiWik count every visit – so also my visits to the site. To avoid this, there is a small handy WordPress function ‘is_user_logged_in()‘ that checks if the current user is actually logged in – or not. Adding a “!” to the function will make the following code only get rendered, if a visitor to your website is not logged in. So for example administrators and editors will not get tracked by PiWik:

<?php wp_footer(); ?>
<?PHP if ( !is_user_logged_in() ) { ?>
<!-- Piwik -->
<script type="text/javascript">
...
<!-- End Piwik Code -->
<?PHP } ?>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *