GET, POST, PUT,and
DELETE methods for a variety of content. In Index, we use the
/post/<id> endpoint with the
DELETE method to trash posts when a user clicks delete. This seemed pretty straightforward, but during testing we ran into a problem: our posts were not being deleted.
Every time we introduce a new feature to Index, or install it on a new machine, we do a few commands to make sure the core experience of the plugin is intact:
- Select and edit posts
- Select and trash posts
- Permanently Delete some trashed posts
- Restore some trashed posts
- Attempt all the above with a user role that can’t do it
Around December of last year, we started using Local for all local WordPress development. When we switched, we did the above steps. Everything worked great, except when we tried to trash posts. No matter what post we tried to delete, we would receive an unauthorized error, and the post was never removed. We double checked that our role should be able to delete posts, and once we confirmed that, we opened up the Postman app and tested some other api requests that require authentication. All of those were working, so why couldn’t we delete a post?
Next, we tried was removing a post from the Gutenberg editor. That worked, so clearly there wasn’t some unfixable issue with the web server. So we opened up our web inspector, reviewed the network requests and discovered that WordPress was using the same
post/<id> endpoint, but it was using
POST instead of
DELETE for the method.
After some digging, we found that Local uses nginx as a web server and only has the
POST methods enabled for api requests (others like
DELETE are not enabled). The solution ended up being simple, but might not be obvious to anyone that doesn’t work with APIs every day.
Send the request with the method set to
POST and add an additional header to your fetch statement:
Doing this ensures broader support for different hosting environments that may not have methods other than GET and POST enabled. Nothing has to happen on the PHP side, and if you are making your own endpoints with
register_rest_route, you can keep setting up your methods per the WordPress documentation website.