Search This Blog

Tuesday, September 19

How to Redirect WordPress 404 Errors to your Homepage or Specific Page

Using .htaccess

One way to redirect 404 pages is to handle them via .htaccess instead of PHP. This has the advantage of being a little more resource friendly on the server since it’s being handled right at the very top. In order to do this, simply add the following line to your .htaccess page:

ErrorDocument 404 /index.php

“index.php” is the default WordPress page for most installations which will direct us to the homepage of the blog. While this accomplishes the redirect, it does nothing for our other requirements – namely sending an email along with the URL that was not found. Of course, we can always check our server logs periodically for 404 errors, but that’s not a scalable way of doing things.

Unless you get a huge number of “not found” errors every day, it’s best to opt for a PHP solution so you can take corrective measures. Not to mention you may not even have write permissions to .htaccess in the first place.

Redirecting 404 through PHP

To intercept 404 pages on your WordPress blog via PHP, simply open up your functions.php file located in your themes folder and paste in the following code before the closing PHP tag:

function redirect_404_send_mail() {
    if (is_404()) {
        $mail_body = 'This page generated a 404 error: ' . $_SERVER['REQUEST_URI'];
        $mail_body .= "\nReferrer : " . $_SERVER['HTTP_REFERER'];
        wp_mail( 'you@youremail.com', '404 page detected', $mail_body);
        wp_redirect( home_url() );
    }
}
add_action( 'template_redirect', 'redirect_404_send_mail' );

Replace “you@youremail.com” above in bold with your own email ID. If you don’t know how to add custom code like this in WordPress, make sure to read my earlier tutorial on the same.

This makes use of the “template_redirect” action hook which fires just before WordPress decides which template to load. We simply intercept that, check for a 404 error message, send an email using the “wp_mail()” function and redirect back to the home URL.

If you want to change that to some other URL on your blog such as the search page for example, you need to include the relative path as a string inside, so you’ll probably have to use something like:

                       home_url('/search');

You can also break up the URL into its constituent parts and construct a search term to passed along as a parameter to your search page to automatically return possibly relevant results to your user. All these are great ways to handle 404 error messages in WordPress. As an example of the above code at work, here’s an email I received from my WordPress installation regarding a 404 error message along with the URL:


No comments:

Post a Comment