Redirect WordPress 404 Not Found Page to Homepage

404 Error

Wow you say .. not again ?

I know this is a tired old subject, but I felt I needed to put my 2cents in.  The trigger for this was a redesign of the M3PCS website.   The site has existed for a number of years, and its pages are indexed by search engines.  So, if anybody clicks on one of those links, we want to do a 301 redirect to the home page.

Since the M3PCS site, like most of the sites we develop and support, is built on WordPress, the question was “how to do this – efficiently“.

A quick Google search turned up two classes of candidates (there were more, but basically these were the main two):

  1. Use a plugin to redirect WordPress 404 pages
  2. Edit the theme’s 404.php template file, and add a wp_redirect()

Problem with #1: not only are many plugins poorly coded, it pollutes the “plugin space” for, what should be, a simple functionality.  Too many plugins already.  So this was a no-go.

Problem with #2: this means changing theme files and/or creating a child theme.  Since we were experimenting with themes, this was obviously not a flexible solution.

So, why not use a Site-Specific WordPress Plugin.  A simple thing like this seems custom-made for that solution.

Simply add the following code (remember that we DO use namespacing — the namespace being “drmagu\siteplugin“):

/* 404 to 301 */
add_action( 'template_redirect', 'drmagu\siteplugin\_404_template_redirect' );
function _404_template_redirect()
{
    if( is_404() ) {
        wp_redirect( home_url( ), '301' );
        exit();
    }
}

So .. no proliferation of plugins, and no theme dependency.  Enjoy.

 

Leave a Reply

You must be logged in to post a comment.