Disable Google Analytics in WordPress theme preview

My Preview Problem
Whilst playing around with some theme switching (having one theme do some stuff, then trigger activating a new theme), I noticed that my Google page visits were going up on a site that is not public. That’s when I realised I had the analytics code for that site in my header and that previewing it was triggering a page hit.

Often it is easier to exclude logged in (or just admin) user page hits, but not always.

The Disabling Solution
The answer is easy, just wrap your code in a logical block using the is_preview() WordPress function.

if( !is_preview() ):
<script type="text/javascript">// <![CDATA[
javascript</span>">
// ]]></script>
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-123456-1']);
    _gaq.push(['_setDomainName', 'tcbarrett.com']);
    _gaq.push(['_trackPageview']);

    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

endif;

Sometimes it is the little things that help!

Using WordPress page templates to restrict access to content

If you have a complex site, perhaps extending WordPress roles by adding your own custom roles. Or even just making extensive use of the core roles. You may have need to quickly create pages that are only readably by certain groups of users. I try to use capabilities over roles for checking these sorts of things, as often you don’t want to exclude users that a role that you consider superior (e.g. checking for ‘subscriber‘ means that ‘editor‘ users cannot see the page, whereas checking for ‘edit_posts‘ means everyone who has a role of ‘contributor‘ or above can view the page).

<?php
/* Template Name: Restricted to Contributors and above */
if ( ! current_user_can( 'edit_posts' ) ) {
  wp_redirect( wp_login_url( get_permalink() ), 302 );
  exit( 0 );
}
?>

If you don’t want it to redirect to the login page, but instead display a message in place of the post content, then you will need to use it as a conditional around the loop. This is a little trickier to give an example of, as it depends