Turn 404 Errors Into Search Results
Sends visitors who hit a missing page to a site search for the words in the broken address, so they land on likely matches instead of a dead end.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
if ( ! is_404() ) {
return;
}
$path = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
if ( '' === $path || preg_match( '/\.[a-z0-9]{2,5}$/i', $path ) ) {
return;
}
$segments = array_filter( explode( '/', trim( rawurldecode( $path ), '/' ) ) );
$last = $segments ? end( $segments ) : '';
$words = trim( preg_replace( '/[^\p{L}\p{N}]+/u', ' ', (string) $last ) );
if ( '' === $words || is_numeric( $words ) ) {
return;
}
wp_safe_redirect( add_query_arg( 's', rawurlencode( $words ), home_url( '/' ) ), 302 );
exit;
} );
Notes
Missing files such as images, scripts and PDFs still return a normal 404.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.