The maybe_redirect_404() WordPress PHP function corrects 404 redirects when NOBLOGREDIRECT is defined.
Usage
maybe_redirect_404();
Parameters
- None
More information
See WordPress Developer Resources: maybe_redirect_404
Examples
Basic usage of maybe_redirect_404()
Redirects a 404 page when NOBLOGREDIRECT is defined in wp-config.php.
// In wp-config.php
define('NOBLOGREDIRECT', 'https://example.com/');
// In your theme's 404.php
maybe_redirect_404();
Custom 404 redirection using maybe_redirect_404() and apply_filters()
Redirects a 404 page to a custom URL specified in a filter.
// In your theme's functions.php
add_filter('blog_redirect_404', 'custom_404_redirection');
function custom_404_redirection() {
return 'https://example.com/custom-404/';
}
// In your theme's 404.php
maybe_redirect_404();
Redirecting 404 pages to the homepage
Redirects a 404 page to the homepage of your site.
// In your theme's functions.php
add_filter('blog_redirect_404', 'redirect_404_to_homepage');
function redirect_404_to_homepage() {
return home_url('/');
}
// In your theme's 404.php
maybe_redirect_404();
Redirecting 404 pages to a specific page
Redirects a 404 page to a specific page by ID.
// In your theme's functions.php
add_filter('blog_redirect_404', 'redirect_404_to_specific_page');
function redirect_404_to_specific_page() {
$page_id = 10; // Replace with your desired page ID
return get_permalink($page_id);
}
// In your theme's 404.php
maybe_redirect_404();
Conditional 404 redirection
Redirects a 404 page based on the user’s role.
// In your theme's functions.php
add_filter('blog_redirect_404', 'conditional_404_redirection');
function conditional_404_redirection() {
if (current_user_can('manage_options')) {
return 'https://example.com/admin-404/';
} else {
return 'https://example.com/user-404/';
}
}
// In your theme's 404.php
maybe_redirect_404();