Ideally, you won’t have any 404 situations in your site. Of course, we all know this is far from being true and “Not found” pages on your site is a common situation that might arise from different reasons, ranging from bad or expired links to simple user typos. In these cases, you can and should build better 404 page by providing some information for them to find the content they were looking for. In this tutorial we will explore one way to build a more friendly 404 page by displaying the WordPress search field populating it with the terms used in the url written by the user.
So the first thing we’re going to see is an example of this technique and how it works on a WordPress site. There’s a 404 page here in ilovecolors that uses the technique described here. In order to visit it, let’s provoke a 404 by visiting:
Look at the search field in the body, it’s populated with the terms used in the resource requested “why mr anderson why” without the dashes.
We’re going to use a bit of PHP to get the name of requested resource and jQuery to put the string into the search field. It’s pretty simple: you need to place this in the 404.php page of your theme where you want to display the search field
$requested_uri = basename($SERVER[‘REQUEST_URI’]);
$terms = str_replace ( "-" , " " , $requested_uri );
$terms = str_replace ( "" , " " , $terms );
$terms = str_replace ( "%20" , " " , $terms );
Let’s go through the code. In the first line, the get_seach_form(); function outputs the search form from your WordPress theme. Then we retrieve the basename of the requested resource, which in the example above, would be “why mr anderson why”. We perform a series of replacements to remove dashes, underscores and change %20 to spaces.
We then start writing a short jQuery to populate the search field. Notice the #content before #s. That’s because we’re using the same form that might be used somewhere else, for instance, in your menu bar or your sidebar. Change this selector to one that works for you to reference the search field in the content body, instead of one located somewhere else. To get the string into the field, we use the val() function from jQuery and that’s all we need.
In order to offer a bit more content to the user, the 404 page from ilovecolors also have a short list of recent posts. However, maybe you could use the knowledge from this tutorial to provide a list of posts relevant to the terms used in the requested url. That would offer more relevant information to them not to mention that we’ll save one search, thus saving time.