# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: 404, search, redirect
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/redirect-404-to-search/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Turn 404 Errors Into Search Results" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
