Tracking 404 pages with Google Analytics is extremely simple. If you have a custom 404 page to handle your 404 pages, you just need to make a simple change in your GA tracking code.
Change this line of code:
pageTracker._trackPageview();
To this:
pageTracker._trackPageview("/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);
So the final GA tracking code for your 404 page should look like this:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-xxxxxxx-x");
pageTracker._trackPageview("/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);
} catch(err) {}
</script>
That’s all there is to it. However, for my purposes I am wanting to use this Analytics code with WordPress. I usually just insert my Analytics code before the closing </body> in my theme’s footer.php file. Since this technique for tracking 404s requires slightly different code than the standard GA tracking code, you can use PHP and the WordPress is_404() function to display the correct code. Just paste this code into your theme’s footer.php file:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-xxxxxxx-x");
<?php if ( is_404() ) { ?>
pageTracker._trackPageview("/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);
<?php } else { ?>
pageTracker._trackPageview();
<?php } ?>
} catch(err) {}
</script>
Please remember to use your Analytics Account ID and not UA-xxxxxxx-x.
Related posts:
Recent Comments