Last updated on September 13, 2023

Redirect 404 Page to Home Page

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Redirect 404 errors to the home page.

When a user attempts to access a page that does not exist on your website, WordPress displays a 404 error message. Instead of showing the error message, you can redirect the user to the homepage of your website.

Option 1: Adding a code snippet

function wpsnippets_redirect_404_to_home() {

   if( is_404() ) {
      wp_safe_redirect( home_url(), 301 );
      exit;
   }
}

add_action( 'template_redirect', 'wpsnippets_redirect_404_to_home' );

The above code snippet uses the add_action() function to add a custom function wpsnippets_redirect_404_to_home() to the template_redirect action. Within the function, the function is_404() checks if a 404 error was set, and redirects the user to the home page using the wp_safe_redirect() function, with a 301 (Moved Permanently) error. You can change this to 302 (Moved Temporarily) if you plan on monitoring your 404 errors and fix any broken links.

Option 2: Editing the 404.php within the theme folder

Here’s how you can achieve the functionality by editing the 404.php within your theme folder.

  1. Open the 404.php file in your theme folder. If your theme does not have a 404.php file, you can create one directly in the theme folder.
  2. Add the following code at the beginning of the file:
wp_safe_redirect( home_url(), 301 );
exit;

This code sets the HTTP response code to 301 (Moved Permanently) and redirects the user to the homepage of your website. Similarly to option 1, you can change this response code to 302 (Moved Temporarily) if you plan on monitoring your 404 errors and fix any broken links.

  1. Save the file.

That’s it! Now, when a user attempts to access a non-existent page, they will be redirected to the homepage of your website.

Please keep in mind that while redirecting 404 pages to the homepage can be useful in certain situations, it may not be the best solution for all cases. If a user is looking for a specific page on your website, redirecting them to the homepage may not provide the information they are looking for. Consider adding a custom 404 page that provides helpful information and links to other parts of your website.

Last updated on September 13, 2023. Originally posted on May 3, 2023.

Leave a Reply