questions

Redirect WordPress 404 page to a specific page

Rate this post

I have built a 404 page in WordPress, but I don’t know how I can make it the 404 page. Working with a free theme here and there is a 404.php file but what would I need to write there in order for this specific page to show up?

So that if a person writes test.com/djashkdajhjkda it goes to test.com/404 and shows that page’s template and content.

I know there are plugins for this, but I’m a bit stubborn and hope there would be a way to resolve this via code. If it’s too complicated to solve via code, I’m happy to take in plugin recommendations.

 

✔️Solution:

Place this code on top of your 404.php file.

<?php
// Here the WordPress will redirect to the page you want with a 301 status code.
// Remember to change the /path-to-go with the URL you like to redirect the users.
// 301 is permanent redirect. 302 is Temporary redirect.
wp_redirect(esc_url(home_url('/path-to-go')), 301);
// And here will stop the file execution.
exit();
?>

An alternative way to achieve the same result it could be to place the following code inside your functions.php:


add_action('template_redirect', 'redirect_if_404');
function redirect_if_404() {
    if ( is_404() ) {
        // Remember to change the /path-to-go with the URL you like to redirect the users.
        // 301 is permanent redirect. 302 is Temporary redirect.
        wp_redirect(esc_url(home_url('/path-to-go')), 301);
        // And here will stop the file execution.
        exit();
    }
}

Generally apply this with caution as it is could damage part of your site SEO.

Leave a Reply

Your email address will not be published.

Back to top button