Sometimes visitors to your site may receive a 404 Error or “Page Not Found”. This may happen when they click on a link that no longer exists or perhaps they typed the address incorrectly. If it’s a business website, a 404 Page Not Found could mean lost money but no matter the type of site, visitors hate 404 Errors. Unfortunately, they will typically leave your site instead of try to find the page they were intending to see.
With this understanding, tracking 404 Error Pages and correcting those errors is good practice and should help keep your visitors happy. Best of all, there’s a simple way to setup Google Analytics to track those pesky 404s for us.
Since I’m a WordPress lover, the code below is specifically meant for WordPress websites although the code can be easily modified for any website platform you use.
Here’s the code to use
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
<?php if ( is_404() ) { ?>
_gaq.push(['_trackPageview', '/404.html?page=' + document.location.pathname + document.location.search + '&from=' + document.referrer]);
<?php } else { ?>
_gaq.push(['_trackPageview']);
<?php } ?>
(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>
Be sure to replace UA-XXXXXXX-X with your Analytics Web Property ID.
Basically what’s happening above is we use the WordPress is_404() conditional tag to check if there’s a 404 error. If an 404 Page Not Found error occurs, this code is output:
_gaq.push(['_trackPageview', '/404.html?page=' + document.location.pathname + document.location.search + '&from=' + document.referrer]);
And for all other pages, this code is output:
_gaq.push(['_trackPageview']);
And it’s really as simple as that. ๐