How to Redirect 404 Page to Homepage in WordPress

404 errors can be frustrating for both website owners and visitors. They occur when a user tries to access a page that doesn’t exist on your site. To maintain a smooth user experience and keep visitors engaged, it’s a good idea to redirect these 404 errors to your homepage. In this post, I’ll show you how to do this using a simple PHP code snippet.

Why Redirect 404 Errors?

When users land on a 404 error page, they might leave your site immediately, increasing your bounce rate. Redirecting them to your homepage helps:

  • Improve user experience.
  • Reduce bounce rates.
  • Ensure visitors find relevant content.

Step-by-Step Guide to Redirect 404 Errors to Homepage

Follow these steps to add a 404 redirection to your WordPress site:

Step 1: Access Your Theme’s 404 Template File

First, you need to access the 404 template file in your WordPress theme. This file is usually named 404.php. You can find it in your theme’s directory:

  1. Log in to your WordPress dashboard.
  2. Go to Appearance > Theme Editor.
  3. Select the 404 Template from the list on the right side.

Step 2: Add the Redirection Code

Once you’ve opened the 404.php file, you need to add the following PHP code at the very top of the file:

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo('url'));
exit();
?>

This code sends a 301 Moved Permanently status to the browser and redirects the user to your homepage.

Step 3: Save the Changes

After adding the code, click the “Update File” button to save the changes.

What Does the Code Do?

  • header("HTTP/1.1 301 Moved Permanently");: This line sends a 301 status code to the browser, indicating that the page has been permanently moved.
  • header("Location: ".get_bloginfo('url'));: This line redirects the user to the homepage URL of your WordPress site.
  • exit();: This ensures that the script stops executing after the redirection headers are sent.

Conclusion

By following these simple steps, you can ensure that visitors who encounter a 404 error on your site are smoothly redirected to your homepage. This helps improve the overall user experience and keeps visitors engaged with your content.

If you found this tutorial helpful, check out my YouTube video for a detailed walkthrough. Don’t forget to subscribe to my channel for more WordPress tips and tutorials!

Feel free to leave a comment below if you have any questions or need further assistance. Happy coding!

Leave a Comment