The blog_redirect_404 WordPress PHP filter allows you to modify the redirect URL for 404 errors on the main site. This filter is only evaluated if the NOBLOGREDIRECT constant is defined.
Usage
add_filter('blog_redirect_404', 'my_custom_blog_redirect_404', 10, 1); function my_custom_blog_redirect_404($no_blog_redirect) { // Your custom code here return $no_blog_redirect; }
Parameters
$no_blog_redirect
(string): The redirect URL defined in NOBLOGREDIRECT.
More information
See WordPress Developer Resources: blog_redirect_404
Examples
Redirect 404 to a custom page
Redirect all 404 errors to a custom page with the slug my-custom-404
.
add_filter('blog_redirect_404', 'redirect_to_custom_404_page'); function redirect_to_custom_404_page($no_blog_redirect) { return home_url('/my-custom-404/'); }
Redirect 404 to an external URL
Redirect all 404 errors to an external website.
add_filter('blog_redirect_404', 'redirect_to_external_url'); function redirect_to_external_url($no_blog_redirect) { return 'https://example.com/404'; }
Redirect based on user role
Redirect 404 errors to different URLs depending on the user’s role.
add_filter('blog_redirect_404', 'redirect_based_on_user_role'); function redirect_based_on_user_role($no_blog_redirect) { if (current_user_can('administrator')) { return home_url('/admin-404/'); } else { return home_url('/general-404/'); } }
Conditional redirect based on query string
Redirect 404 errors to different URLs based on the presence of a query string.
add_filter('blog_redirect_404', 'conditional_redirect_based_on_query_string'); function conditional_redirect_based_on_query_string($no_blog_redirect) { if (isset($_GET['custom'])) { return home_url('/custom-404/'); } else { return home_url('/general-404/'); } }
Redirect to a random post
Redirect 404 errors to a random post on the site.
add_filter('blog_redirect_404', 'redirect_to_random_post'); function redirect_to_random_post($no_blog_redirect) { $args = array( 'posts_per_page' => 1, 'orderby' => 'rand' ); $random_post = get_posts($args); return get_permalink($random_post[0]->ID); }