If you search for “wordpress rest api filter response not found” or something like WordPress, REST API and 404’s, you’ll find a lot of users attempting to fix permalink issues or improperly set up custom REST endpoints. That is until I got my Google foo right and came across Bill‘s post on Handling Not Found Errors in the WordPress REST API. ππΌ
Quoting from Bill’s post
The only trouble is in how WordPress handles not found errors. When you make a request to the API using an ID that doesnβt exist, you end up with a response that looks like this: Gist
Basically WordPress only handles not found errors for <id>
endpoints like wp-json/wp/v2/posts/<id>
. Which if passed a numeric value that doesn’t match a post ID would return the following code plus a response status of 404 Not Found
.
{
"code": "rest_post_invalid_id",
"message": "Invalid post ID.",
"data": {
"status": 404
}
}
That’s great! What about post queries by slug?
Making a request for an item using a slug that doesn’t exist (something like wp-json/wp/v2/posts?slug=<slug>
), youβll get a response status of 200 OK
and an empty body array. This isn’t ideal.
[]
The following is where I diverged from Bill’s posts since he is using a single page app and axios/javascript. The following is how you should handle “Not Found” errors in the WordPress REST API for queries by slug at the PHP level.
Validating queries by slug
We will use a few WordPress actions and filters to modify the REST API response. I have written a class for this scenario for my current application use case, but the following will be an adaptation that anyone can use:
Please note the headers in the plugin. You should be using the latest version of WordPress, at the present time it’s 5.4.1
, and this code also requires your PHP version to be >= 7.3
.