Create a custom WordPress function to redirect 404 pages to the home page by adding the following code to your theme's functions.php file or in a custom plugin file:
function redirect_404_to_home() {
if (is_404()) {
wp_redirect(home_url('/'));
exit();
}
}
add_action('template_redirect', 'redirect_404_to_home');
Here's a breakdown of how the function works:
-
function redirect_404_to_home() { ... }: This defines a custom function called redirect_404_to_home.
-
if (is_404()) { ... }: This checks if the current page is a 404 error page.
-
wp_redirect(home_url('/'));: If the current page is a 404 error page, it redirects the user to the home page using wp_redirect() function.
-
exit();: This stops the execution of the script after the redirection to ensure that the user is immediately redirected without processing any further code.
-
add_action('template_redirect', 'redirect_404_to_home');: This hooks the redirect_404_to_home function to the template_redirect action in WordPress, so the function is executed during the template loading process.
By adding this code to your WordPress site, any 404 error page will automatically redirect users to the home page. Remember to always backup your theme's functions.php file or your custom plugin before making changes.