0

I have this code registered to the "parse_query" action which attempts to trigger a 404 based on the availability of an API asset. My implementation is based on this answer to another question.

public function throw404($query)
{
    if ($this->avorgApi->getPresentation($query->get("presentation_id"))) return;

    $query->set_404();
    $this->wp->call("status_header", 404);
}

($this->wp->call(...) is just a simple wrapper object that allows me to stub out and spy on my calls to WordPress. It calls the status_header function just the same as if I had called it directly.)

The throw404() function is registered in the object's __construct() method, like so:

$this->wp->call("add_action", "parse_query", [$this, "throw404"]);

When the requested asset is missing and the 404 is triggered, I get the following error:

Cannot modify header information - headers already sent

I discovered that I can prevent the error by commenting out the second to last line in the function ($query->set_404();), but neither is the 404 thrown, which defeats the purpose.

How can I resolve this?

  • You haven't shown where or how your throw404() function is called. – Peter HvD Aug 6 '18 at 9:52
  • @PeterHvD I've added the call to the question. Could you take a look at it again? – Nathan Arthur Aug 10 '18 at 18:17
  • What happens if you remove the wrapper object from the equation and call the status_header function directly within the same throw404 function? – Peter HvD Aug 12 '18 at 13:04
0

I figured it out. Basically, the problem was that I also had registered a URL rewrite that set page_id as a query var, which overrode the 404 and loaded the referenced page. I fixed this by adding this line to my throw404() function:

unset($query->query_vars["page_id"]);

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.