WordPress: How to redirect 404 errors to plain HTML pages

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?

Jordi Plana

Jordi Plana

I'm Jordi Plana, a software developer in his late twenties.I've been involved in web development for the past 12 years. It all started with a website dedicated to playing board games when I was a teenager, and since then I had the chance to make websites for all kind of businesses, organizations and individuals.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>