I have a couple of pages that are populated with data from non-Wordpress tables in my database. https://pageURL/?asi_id=12345 causes the DB-lookup to get the correct data. If someone uses the wrong query-string I want a 404 error generated. I am at a point long after the headers have been generated when I discover the issue. I have tried several code fragments from this forum and others. They cause the "404-template" to be displayed by the status code is still 200 and not 404. I suspect that Google wants the correct status code.

Any ideas how I can force the error at this point in WP's loop?

  • 2
    To send a real 404 you'd need to send the 404 status code via HTTP headers, which needs to happen before any markup is sent, if you're already in the loop then it's too late for that. The best you could hope for is just the template to look like a 404. The moment even a single character of the page gets sent out, the opportunity to send the HTTP header is gone – Tom J Nowell Jul 8 '19 at 21:14

The short version is that you will need to do the lookup much sooner. As pointed out in comments, a 404 status can only be sent with the headers.

There are a few ways that you can solve this issue. I would do it with a class. That class would use a few hooks but most importantly, one would be early on, say "init", for example. That would be when I would have it figure out if it will be needed and do the lookup. That result, I would store in a protected variable.

Then, when it comes time to output the data, I could have another function in the class (called a method) just deal with the output (as the lookup already happened).

This would allow you to respond 404 if the lookup failed long before any content is sent.

There are other ways using hooks and global variables but I prefer classes.

  • If you need help getting to grips with hooks ask about them here.

  • If you want help understanding classes, that's Stack Exchange.

  • If this answer is not helpful enough, another one will be along sooner or later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.