Best 404 page for blog with autosearch function

When visitors of your site come to a bogus page address, they are normally shown a 404 error page. The page just says content does not exist and that’s it. Not very useful! Especially if the content does exist, and you only changed the permalink structure. So the users clicking on old links can not reach the page at the new address, which is bad for pagerank, social media sites and other link sources you can’t alter.

A perfect 404 page would automatically search the content of your site according to the URL entered, and bring out suggestions to the user.
To achieve that, open your theme’s 404.php template for editing. Clear it all up and insert the following code:

<?
$search_term = substr($_SERVER['REQUEST_URI'],9);
$search_term = urldecode(stripslashes($search_term));
$search_url = 'http://YOUDOMAIN.COM?s=';
$full_search_url = $search_url . $search_term;
$full_search_url = preg_replace('/ /', '%20', $full_search_url);
$full_search_url = preg_replace('/-/', '%20', $full_search_url);
$full_search_url = rtrim($full_search_url,"/");
$full_page = implode("", file($full_search_url));

print_r($full_page);
?>

You must change several values to make it work.
The numeric in the $search_term = substr strips away the symbols after your domain name. In this example, it deletes nine symbols, which is the date (/YEAR/MO/) WordPress adds in the permalinks structure used. Trim it to your specific needs.
The other important line is $search_url. This is the beginning of the search URL of your Wodpress. To find it out, search for anything on your blog with the CMS built-in search function. For WordPress, it’s normally your domain name plus ?s=.

Save the page. Now every time someone reaches an non-existent URL on your blog, the site will automatically search for relevant articles using the URL as the search keywords.

Leave a Comment