Simple Way to Track 404 Error Pages with Google Analytics

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. :-)

JoshStauffer.com runs on the Genesis Framework

Genesis Framework

Genesis empowers you to quickly and easily build incredible websites with WordPress. Whether you're a novice or advanced developer, Genesis provides the secure and search-engine-optimized foundation that takes WordPress to places you never thought it could go. It's that simple - start using Genesis now!

Take advantage of the 6 default layout options, comprehensive SEO settings, rock-solid security, flexible theme options, cool custom widgets, custom design hooks, and a huge selection of child themes ("skins") that make your site look the way you want it to. With automatic theme updates and world-class support included, Genesis is the smart choice for your WordPress website or blog.

Become a StudioPress affiliate

Speak Your Mind

*