Smart 404 page

Wordpress automatically manages the page that appears when the user gives the URL of a page that does not exist.

In fact it is sufficient to put a 404.php file alongside the other files in the theme, for the contents of this file is displayed on URL errors.

Most of the time, it is a banal and dreary message which is presented to visitors:

Error 404 - Page not found.

It is not very appreciable. The least we can do is offer he other pages to see, or better yet, find the article that is most related to what he was looking for.
For this, a condition is that the links are significant and mode of keywords, you could not guess what a visitor searches when he types the bad number of an article!
Most webmasters using Wordpress configure the permalink in the administering panel, with the %postname% command.

Code of the 404 page

The structure of the smallest error page, so the contents of the 404.php file, is as follows:

Searching for similar pages

From the words in the URL passed by the visitor, it is also possible to search in the titles of posts, to find that which would be closest to what is asked.

Note that Wordpress itself has a recovery system of erroneous URL, using the first words in the URL and seeking an article that begins with these words. The algorithm that is proposed works when Wordpress fails.

- Short words are eliminated, unless the URL contains only two.
- A WHERE clause is created that consists of a series of AND comparing the words in the titles of articles with the words in the URL.
- Entries of type revision or attachment are skipped thanks to the condition: post_type=post.

The query in a clear form becomes as following:

SELECT post_title, post_name FROM $table WHERE (post_title LIKE '%word1%') AND
(post_title LIKE '%word2%') ...etc... AND
post_type = 'post"

From that are obtained two lists, the titles and URLs, and we construct a list of links with <a> tags.

Using related plugins

We could develop this algorithm to improve relevancy. But instead of remaking the world, why not use a related plug-in, a list of posts with similar subject?

Failing to have the tags of the article, you create a list from the URL.