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 …
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
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:
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
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(); )
Create
404.php
template file in your theme and customize as needed (adding your plugin output or whatever). You mention defined in your theme, what exactly is wrong with this approach for you?Codex Creating an Error 404 Page
Since most answers here are very old and I still stumbled upon this post, I’m adding this for good measure. It looks like WordPress introduced a new hook in version 4.5.0:
https://developer.wordpress.org/reference/hooks/pre_handle_404/