Redirect 404 Error to another page

How can I redirect all or part of the error pages to another page?

Website will generate a “404 Not Found” web page when a user attempts to follow a broken or dead link.

As wordpress intercepts 404 errors to redirect them to the 404.php template, setting a rule in the htaccess file will have no effect.

One solution is to modify the 404.php template and integrate a redirection with this type of code:
[php]
<?php
header(“HTTP/1.1 301 Moved Permanently”);
header(“Location:”.get_bloginfo(‘url’)); exit();
?>
[/php]

Another (better) solution is to add a snippet in the functions.php file to redirect all or part of the traffic to another page.

Redirect all 404 to one page

[php]
/**
* Redirect 404 to specific page
*/
add_action( ‘template_redirect’, ‘wpster_redirect_not_found’ );
function wpster_redirect_not_found() {
if( is_404() ) wp_redirect( home_url( ‘/landing/’ ) );
}
[/php]

If a references is not found, redirect to list of references (category)

[php]
/**
* Redirect 404 references to category
*/
add_action( ‘template_redirect’, ‘wpster_redirect_not_found_references’ );
function wpster_redirect_not_found_references() {
if( is_404() && is_singular(‘your-custom-post-type’) ) {
wp_redirect( home_url( ‘/references/’ ) );
exit();
}
}
[/php]

 

Submit a Comment

Your email address will not be published. Required fields are marked *