So I was reading through the blogosphere this morning, and I came upon this article: Creating User Friendly 404 Pages. Since I find myself also somewhat annoyed at bad 404 pages (hence the reason why I use the ErrorZilla firefox add-on), I decided to become a part of the solution, and not just bitch at the problem.
The goal here is to have our 404 pages fit nicely into the whole WordPress experience. Think of the 404 page holding hands with WordPress, sitting around the campfire, singing Kumbaya (had to look the spelling of that one up on Wikipedia). Now you get the right idea.
So, the first step is to have 404 pages redirect to your blog. The easiest way to do this is to trigger the automatic WordPress 404 behavior by sending the user to a bogus part of the blog. To do this, in the top-level of your blog directory, create an .htaccess file that contains the following (for Apache; for IIS, you are on your own, but I’m sure it is simple enough):
ErrorDocument 404 /index.php/error
Since “error” is (assumedly) not an actual page, this triggers the default 404 page, which depends on your theme. If, like me, you are using the default theme, you get a wholly non-contextual “it isn’t here” type of deal, but at least it has the sidebar and header. The next step is to add some more useful information to this page.
With Apache, when it does a 404 redirect, it gives you some useful information. What we are looking for is in the variable REDIRECT_URI, which you can grab in php by the variable $_SERVER['REDIRECT_URI'].
We can use this, in the 404.php page, to give some contextual information, and allow the user to search for what they could not find. Optionally, I’m sure you could set it up to automatically perform a search for the information. I didn’t go that far, since about 15 minutes is the max I’m willing to spend on something like this.
So, if you are using the default theme, you can find the 404.php page here:
/wp-content/themes/default/404.php
You should see in that file a div, with some other directives for including the sidebar, header, and footer. You are going to replace that div with code that detects the redirect URI and gives you a search form that searches for pieces of the URI they typed in, with certain strings replaced with spaces (like ‘.’, ‘/’, ‘html’, ‘php’, etc.). Since WordPress sucks at letting me paste in code, here is a link to a text version of the php file: 404.php.
So, go ahead and search for something silly. Try, let’s say, http://noahsmark.com/this/sucks, or http://noahsmark.com/404.
Also, I’m sure there are more strings you would want to remove from the URI, but, again, 15 minutes is the maximum time I’m willing to spend.
So, there you have it. Enjoy!