Gearside Design

Enhanced 404 page with a Google Custom Search Engine

There are lots of cheeky 404 pages when a user arrives at a page that is not found, but even the best joke won’t help ease a user’s frustration!

Let’s make our 404 pages more helpful by using the clues we’re given to make some suggestions for the user. I’ll show you how to do it using a Google Custom Search Engine and I’ll include another method for WordPress users to do an internal search too.

What clues do we have?

Unless you’ve got a major issue on your server, you’ll generally have some keywords in the URL when the user arrives at a 404 page not found error. We can separate these keywords and plug them into a Google search (limited to your domain) to try to find the page they were looking for. We’ll also run a query on the database at the same time to come up with a few other suggestions.

Creating a Google Custom Search Engine

Visit the Google Custom Search dashboard and click the “Add” button. Type in your domain and give this search engine a name, then click “Create”.

Open the Setup page for your newly created search engine (if you’re not taken there automatically). Don’t worry about the visual settings, but click on the “Search engine ID” button. For this feature we’ll be using the API to search automatically so the user doesn’t need to take any extra steps.

Setting up the Google Custom Search API

Next, go to the Google APIs Developers Console and create a new project if you haven’t already. Select your project and in the upper left (behind the “hamburger” icon) navigate to the API Manager. Under the “Other popular APIs” click on “Custom Search API”. At the top, enable this API.

Note that the free tier of this API is limited to 100 queries per day. It can be upgraded if needed here.

Now generate a Browser Key by clicking on “Credentials” on the left and choosing “API Key” under the “Create credentials” dropdown button.

Collecting the search phrase

We’ve got everything we need to start coding JavaScript. You’ll need to decide how you listen for 404 pages. In WordPress, the body tag has the class of “error404”. I’ll be using jQuery in the following examples.

To get the search phrase, we’ll take the window.location.pathname and replace the plus signs with actual spaces. Here’s what that line looks like:

JavaScript

var phrase = decodeURIComponent(jQuery.trim(window.location.pathname.replace(//+/g, ‘ ‘)));

From there I made a function that accepts this phrase parameter called trySearch(phrase). It creates a query parameter object, applies the API, and makes the request to Google. Here is the entire function:

JavaScript

function trySearch(phrase){
	var queryParams = {
		cx: CUSTOM_SEARCH_ENGINE_ID_HERE, //Use your Google Custom Search Engine ID here
		key: BROWSER_API_KEY_HERE, //Use your Browser API Key here
		num: 10,
		q: phrase,
		alt: 'JSON'
	}
	var API_URL = 'https://www.googleapis.com/customsearch/v1?';

	// Send the request to the custom search API
	jQuery.getJSON(API_URL, queryParams, function(response){
		if ( response.items && response.items.length ){
			if ( response.items[0].link !== window.location.href ){
				//Title of suggested page: response.items[0].title
				//URL of suggested page:response.items[0].link
			}
		}
	});
}

Notice in the response we are only interested in the first result, so if the response has items in it and the first item does not match the current page URL we can use the suggested page. How you present this to your user will be up to you.

As enticing as it may be to automatically redirect to this page, I would strongly advise against it. The 404 headers have already been sent, so Google may think you’re being shady by redirecting on 404 pages.

Supplementing with some internal suggestions

To further support the Google Custom Search, let’s run a search of our own by querying the WordPress database.

On 404 pages in PHP, let’s set a variable to the keywords like we did in JavaScript above:

PHP

$url_compontents = parse_url($url)
$slug_keywords = end(array_filter(explode(‘/’, $url_compontents[‘path’])));

Next, we’ll create a query to grab four suggestions:

PHP

$error_query = new WP_Query(array(‘post_status’ => ‘publish’, ‘posts_per_page’ => 4, ‘s’ => str_replace(‘-‘, ‘ ‘, $slug_keywords)));

I like to check to see if the first result is an exact match of the keywords to emphasize that result. You can do that with a simple conditional:

PHP

if ( $slug_keywords == $error_query->posts[0]->post_name ){ … }

Showing the results

Finally, let’s loop through the suggestion results on the 404 page (if there were any). This is done with a simple loop. Obviously, customize the markup as needed to match your site.

PHP

<?php if ( $error_query->have_posts() ): //$error_query is defined in nebula_functions.php ?>
	<div id="error-page-suggestions">
		<h2>Suggestions</h2>
		<?php while ( $error_query->have_posts() ): ?>
			<?php $error_query->the_post(); ?>
			<h3><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
		<?php endwhile; ?>
		<p><a href="<?php echo home_url('/'); ?>?s=<?php echo str_replace('-', '+', $slug_keywords); ?>">View all results &raquo;</a></p>
	</div>
<?php endif; ?>

Notice the link to view all results by linking to ?s= of the detected keywords. This is useful since we’re only checking four suggestions. I also like to provide a search form to give more options to the user.

Summary

You’ll find all sorts of approaches to 404 pages online. Some are simple “Error 404: Page Not Found” text and others make an attempt at humor, but I’ve found that the best approach is being as helpful as possible. That’s not to say you can’t make something unique as well, but making the user laugh isn’t as good of a conversion as getting them the content they were looking for in the first place!