Goal: Make a POST request to the WordPress API
Indeed, make your POST request to
example.com/wp-json/wp/v2/posts. Make sure pretty permalinks are turned on!
with new post information.
This would be the information being
POST'd, and should take the same format as when going into
Take the new post information, validate it
WP will do this automatically for its own fields. If you wished to register a new endpoint, you could declare all the possible fields, wether they're required or optional, and sanitising and validation callbacks. The API will take care of returning any error objects back to the client in the appropriate format with the correct HTTP code
and if information is valid and user has privileges add the post to the database.
The REST API already checks this, but if you add your own endpoint you can specify a capability, or even a more in depth callback
I assume that I would need a plugin to expose a new route and have it handle all the requests to that route.
If you desire a custom endpoint then yes, you will need to use
register_rest_route and provide the needed information.
Documentation on Adding Custom Endpoints
I have a headless setup with nextjs and I need the frontend user to be able to add a post. I can figure out the frontend half, it's the backend half I'm having issues with.
At this point it's a standard REST API, with 2 differences:
- WP will want the user to be logged in with cookies
- WP will want a valid nonce
If you enqueue the
wpapi script, it'll insert the URL to the REST API, as well as a valid nonce you can use. Assuming this is all on the same domain. You can then use the
wpapi library to make the requests, or
If you want to interact with a remote WP install on a different domain/server though, you'll need a plugin to implement authentication, such as OAuth1/2/etc