How to Force 404 Errors in WordPress

Sometimes you have to force 404 errors in WordPress, either because the 404 pages are not properly configured, or sometimes WordPress itself or caching plugins may make 404 errors impossible. I tried to create 404 pages to fix Google penalties, but even after unpublishing posts, the  site HTTP response headers still displayed a 200 OK working page.

404 page

I found that there are several ways to forcing 404 errors in WordPress…

Check 404 file exists

It is possible that WordPress is not configured properly to show a 404 page when it is required to do so. First ensure your active WordPress theme has a 404.php file in the active themes folder. If not, you can simply save a 404.php file with following text.

<?php get_header(); ?>
    <h1>Page Not Found</h1>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

Check 404 file works

Then ensure that your server can identify the location of your 404.php file. First test the exact location of the file in your browser to see it loads. Then you can add the following code on top of your WordPress folder .htaccess file to let it find the file.

ErrorDocument 404 /index.php?error=404

If your WordPress installation is in a subdirectory called ‘abcd’, you might use this code.

ErrorDocument 404 /abcd/index.php?error=404

Disable Quickcache 404 Caching

We had this another issue with 404 files that at first instance it showed a 404 error, then QuickCache cached the file to create a html file for that error page. Then if you check the site headers the page gave a 200 OK status meaning the page existed well  (this was similar to the feed caching issue). So we added this code to our 404.php template page in the first line even before the header coding was called for.  Add the following code

if (is_404()) {
    define('QUICK_CACHE_ALLOWED', false);

Disable WordPress Smart Redirect

WordPress is a smart blogging tool and redirects 404 errors to best possible matching urls which it seems fit based on the visited url keywords. Many of my 404 urls were being redirected to similar working urls, which might or might not be relevant but had similar keywords. So we need to add the following code to theme functions.php to prevent this WordPress redirection ability to get pure 404 errors.

remove_filter('template_redirect', 'redirect_canonical');

Test Site Response Headers

So mostly this should take care of your 404 errors and you can test them with popular site HTTP headers checking tools like Web Sniffer or HTTP Response Headers to find out if your 404 errors are actually working.

404 not found error

If you get this ‘404 Not Found’ error after repeatedly refreshing the result you are done.