WordPress 404 Redirect to Home

%%title%% %%sep%% %%sitename%%
WordPress 404 Redirect to Home

Redirect 404 errors to the homepage in WordPress by adding a simple code snippet to your functions.php file. Improve user experience and keep visitors engaged by preventing broken links from leading to dead ends.

Someone lands on a dead URL, hits a bare 404, and bounces. It stings, so the tempting fix is to send every 404 straight to the homepage. You’ll see the snippet for it all over the web. Here it is, and here’s why we’d steer you away from using it as a blanket rule.

The snippet

Drop this in your theme’s functions.php. It hooks template_redirect, checks for a 404, and sends the visitor home with a 301.

/**
 * Redirect 404 errors to the homepage.
 *
 * This function checks if the current query is a 404 error and,
 * if so, redirects the user to the site's homepage with a 301
 * permanent redirect status.
 */
function homepage_redirect_404() {
    global $wp_query;

    // Check if the current query is a 404 error
    if ( $wp_query->is_404 ) {
        // Redirect to the homepage with a 301 status code
        wp_redirect( get_bloginfo( 'wpurl' ), 301 );
        exit; // Always call exit after redirect to stop further execution
    }
}

// Hook the function to run before the template is loaded
add_action( 'template_redirect', 'homepage_redirect_404', 1 );

Read this before you ship it

Google treats a redirect from a missing page to the homepage as a soft 404, and it discourages the pattern. A dead URL should return a real 404. When you 301 a broken URL to your homepage, you tell search engines the homepage now lives at that address too, so Google keeps crawling the dead URL and can drop it from useful results. It doesn’t rescue your backlinks either; it just points them at a page that has nothing to do with what the visitor wanted.

Better plays, in order:

  • Build a helpful 404 page. Return a proper 404, then give people a search box and links to your popular pages. That keeps them on the site without lying to search engines.
  • 301 to the real replacement. If a page genuinely moved, redirect that one URL to its specific new home, not to the homepage.

The homepage-redirect trick works on the day you add it. It’s the SEO bill three months later that gets you. Reach for the custom 404 page first, and save 301s for the moves that actually have a destination.

Next: WordPress Robots.txt for Improved SEO and UX

Leave a Comment

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


Scroll to Top