WordPress: How to redirect 404 errors to plain HTML pages

Posted by & filed under Web development, Wordpress.

Scenario

Sites with high volume of content may have some moved, deleted or badly referenced content. This situation will cause a 404 http error.

Problem

In high performance sites the previously described situation can be a resource problem. It is not necessary that we load completely the site to show a 404 error page.

Solution

Loading a plain HTML page will result easier for our web server than loading a complete CMS instance.

With a few lines of code we can hook the WordPress normal loading in order to determine if a 404 error has been produced. If we detect this situation we will make a redirection to a plain HTML page, interrupting the normal WordPress loading process.

Copy and paste the next code snippet into your functions.php, in your theme folder. Create a new plain HTML, name it 404.html and upload it to the site’s root.

add_action('wp','determine_if_404'); 

function determine_if_404(&$arr){
    global $wp_query;
    
    if($wp_query->is_404){
        header('Location: '.get_bloginfo('siteurl').'/404.html');
        die;
    }
}

Comments, questions, suggestions?

Leave a Reply