To create a 404 redirect within a WordPress template, you can add custom code to your theme’s functions.php
file. This code will detect when a 404 error occurs and then redirect the user to a specific page or URL.
Here’s an example of how you can do this:
- Backup Your Website: Before making any changes to your theme files, it’s always a good practice to back up your website to avoid any potential issues.
- Edit
functions.php
File:
- Log in to your WordPress dashboard.
- Go to “Appearance” > “Theme Editor.”
- In the Theme Editor, locate and click on the
functions.php
file on the right-hand side. This is where you will add your custom code.
3. Add the 404 Redirect Code:
- Insert the following code at the end of your
functions.php
file:
function custom_404_redirect() {
if (is_404()) {
wp_redirect('https://example.com/new-page', 301);
exit();
}
}
add_action('template_redirect', 'custom_404_redirect');
Replace 'https://example.com/new-page'
with the URL of the page where you want to redirect users when they encounter a 404 error.
- Save the Changes: After adding the code, click the “Update File” button to save your changes.
- Test the Redirect: To test the 404 redirect, you can intentionally visit a non-existent page on your website, and you should be redirected to the specified URL.
Please note that it’s important to choose a relevant and informative page for redirection, such as a custom 404 error page or your website’s homepage, to provide a good user experience. Also, make sure that the URL you’re redirecting to is correct.
Additionally, using a plugin dedicated to handling 404 errors and redirects, such as “Redirection” or “404 to 301,” may provide more advanced and user-friendly options for managing 404 redirects if your needs go beyond a simple redirect in the theme’s functions.php
file.