Using WordPress ‘pre_redirect_guess_404_permalink’ PHP filter

The ‘pre_redirect_guess_404_permalink’ filter allows you to short-circuit the URL guessing process for 404 requests in WordPress.

When you return a non-null value from the filter, it will skip the URL guessing and use the provided value instead.

Usage

add_filter( 'pre_redirect_guess_404_permalink', 'your_function_name', 10, 1 );

Parameters

  • $pre null|string|false
    • Determines whether to short-circuit the URL guessing process for a 404 request.
    • Default value: null (continues with the URL guessing process).

Examples

Disable URL guessing for 404

function disable_url_guessing( $pre ) {
    return false;
}
add_filter( 'pre_redirect_guess_404_permalink', 'disable_url_guessing', 10, 1 );

This example disables the URL guessing for all 404 requests, by returning false.

Custom 404 URL for specific post type

function custom_404_for_post_type( $pre ) {
    if ( is_404() && get_query_var( 'post_type' ) == 'custom_post_type' ) {
        return '/custom-404-page/';
    }
    return $pre;
}
add_filter( 'pre_redirect_guess_404_permalink', 'custom_404_for_post_type', 10, 1 );

This example provides a custom 404 URL for a specific post type called custom_post_type.

Custom 404 URL based on the request

function custom_404_based_on_request( $pre ) {
    if ( is_404() && strpos( $_SERVER['REQUEST_URI'], 'product' ) !== false ) {
        return '/product-not-found/';
    }
    return $pre;
}
add_filter( 'pre_redirect_guess_404_permalink', 'custom_404_based_on_request', 10, 1 );

This example returns a custom 404 URL when the requested URL contains the word ‘product’.

Redirect to the homepage on 404

function redirect_to_home_on_404( $pre ) {
    if ( is_404() ) {
        return home_url();
    }
    return $pre;
}
add_filter( 'pre_redirect_guess_404_permalink', 'redirect_to_home_on_404', 10, 1 );

This example redirects users to the homepage when a 404 error occurs.

Custom 404 URL for missing images

function custom_404_for_images( $pre ) {
    if ( is_404() && preg_match( '/\.(jpe?g|png|gif)$/i', $_SERVER['REQUEST_URI'] ) ) {
        return '/image-not-found/';
    }
    return $pre;
}
add_filter( 'pre_redirect_guess_404_permalink', 'custom_404_for_images', 10, 1 );

This example provides a custom 404 URL for missing images (JPEG, PNG, and GIF).