google analytics Icon Logo
me@grafxflow

Written by me@grafxflow

18 Mar, 2013

0

2,230

Hide google analytics on preview posts/pages

In WordPress you may have added (by hand) your google analytics to the footer.php file. But this brings a problem that you may not have noticed. While previewing a post/page your are still telling google to analyse this page even though it is not live. So the code needs to be hidden.

The preview URL will look something like this www.yourwebsite.co.uk/?p=1234&preview=true.

1. In your footer.php you will have something like this.

<script type="text/javascript">

  var _gaq = _gaq || [];

  _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);

  _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);

  })();

</script>

2. You need to add the following to the footer.php.

<?php 
if( !is_preview()) {
  /* Add Google Analytics Code Below: */
?>
<script type="text/javascript">

  var _gaq = _gaq || [];

  _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);

  _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);

  })();

</script>
<?php
}
?>

3. In short you are adding...

<?php 
if( !is_preview()) {
  /* Add Google Analytics Code Below: */
?>

<?php
}
?>

Add comment

Smart Search

119 Following
50 Followers

me@grafxflow

Hull, United Kingdom

I am a Full-stack Developer who also started delving into the world of UX/UI Design a few years back. I blog and tweet to hopefully share a little bit of knowledge that can help others around the web. Thanks for stopping by!

Follow