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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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
Method 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;
Method 3
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0