Are there any hooks that alter the 404 logic?

Provided you have a 404 page defined in your theme, WordPress will display a 404 page if “tag” is defined in $wp_query->query_vars, and there are no posts matching that tag.

I’m writing a plugin that displays some information on each page, in addition to posts. I’d like to alter the 404 logic so that the 404 page gets displayed if there are no posts matching a tag and the plugin cannot pull up any data matching that tag. If the plugin can find data, I’d like to show a normal page, regardless of whether there are posts on that page or not …

Read More

I’ve been Googling, reading code, reading the codex, and poking around here, and haven’t been able to figure out where WordPress triggers that 404, and how I can override it. (I have a feeling it might have something to do with status_header() in functions.php, but it’s not clear how and when I need to hook into it).

Any help/ideas/enlightenment appreciated.

Thank you,

~ Patch

Related posts

Leave a Reply

4 comments

  1. After a bit more slogging through code and Googling, I found the answer. It’s contained in this thread (see Otto42’s post), but for the record, adding the following to your plugin will override the 404 handling for the conditions you specify:

    add_filter('template_redirect', 'my_404_override' );
    function my_404_override() {
        global $wp_query;
    
        if (<some condition is met>) {
            status_header( 200 );
            $wp_query->is_404=false;
        }
    }
    

    Note that you need to set “is_404” to false before PHP outputs headers, which is why hooking it in the template_redirect logic is a good idea.

    ~ Patch

  2. I needed to do the same for a custom project where there was always a 200 page, and found you can also simply add this to the top of your template file ( above get_header(); )

    global $wp_query;
    status_header( 200 );
    $wp_query->is_404=false;