How-to: WordPress 404 errors with Google Analytics

Google Analytics is a great tool, and not just because it is free. But, there are always little things I run into that Google Analytics doesn’t do that I wish it would. One example: tracking 404 requests in WordPress.Currently, when WordPress 404’s, it doesn’t redirect to a 404 page proper, but displays WordPress’ 404 page content at the request location that was originally requested. The way that this is interpreted by Google Analytics is as a successful page request. If you were to request http://smcandrew.com/some-nonexistent-page, I just get an entry in my Google Analytics for that page, which, unless I review my statistics at a granular level, I will miss. What I want to know is what page requests are 404ing in the event that there are pages that I haven’t 301 redirected correctly, or, that another site has linked to intadvertently.Luckily there is a way to report 404’s by customizing the Google Analytics JavaScript for these situations.I keep my Google Analytics code in my footer.php page, but this should work regardless of which PHP file has the Google Analytics script.How to track WordPress 404 requests in Google Analytics: Here is the stock Google Analytics JavaScript code snippit:

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script><script type="text/javascript">	_uacct = “##-#######-#”;urchinTracker();</script>

Here is a modified JavaScript snippit which logs the request as to a 404 page:

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script><script type="text/javascript">	_uacct = “##-#######-#”;urchinTracker(”/404?page=” + _udl.pathname + _udl.search);</script>

So, if we can just determine when a 404 request is made, we can have WordPress insert the right javascript code. Luckily, WordPress makes that easy to do. Here’s the final code, which I’ve inserted into my footer.php file, just above the tag:

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script><script type="text/javascript">_uacct = "UA-1449530-1";<?php if ( is_404() ) { // custom 404 code for Google Analytics ?>urchinTracker("/404?page=" + _udl.pathname + _udl.search);<?php } else { // Google Analytics for all other pages ?>urchinTracker();<?php } ?></script>

Now all requests which 404 will be logged as a request to ‘404′ and will also indicate what specifically was requested. For example, in the earlier scenario (the request for a non-existent page at ‘http://smcandrew.com/some-nonexistent-page’), my Google Analytics would report the following in my Content > Top Content report:/404?page=/some-nonexistent-pageHope this is of help to other WordPress users out there!

Tags: , , , ,
New around here?
You may want to subscribe to my RSS feed. Thanks for visiting!

No comments yet »

Your comment

Close
E-mail It