All 404 implementations seem to revolve around showing related content. I think we can do one better by automatically searching for the missing post… How can this be done?
2 Answers
This can be done in two easy steps.
-
Upgrade your site search with a plug in, such as Relevanssi (optional).
-
Add the following code in functions.php or via Code Snippets (thx to @Howdy_McGee and Russell Jamieson for ideas!)
function wpse_204310() {
global $wp_query;
if( is_404()
&& !is_robots()
&& !is_feed()
&& !is_trackback()
) {
$uri = $_SERVER['REQUEST_URI'];
$clean = str_replace( "https://wordpress.stackexchange.com/", "%20", $uri );
$clean2 = str_replace( "-", "%20", $clean );
wp_redirect( home_url( "/?s={$clean2}" ) );
exit();
}
}
add_action( 'template_redirect', 'wpse_204310' );
That’s it. This code will parse the url for the blog title, and pass it along to your search page. All transparent to the user. This assumes a simple permalink structure, such as domain.com/post-title