Extending wp JavaScript base class to make a post request to a custom REST endpoint

I’ve defined a REST endpoint /my-plugin/v1/post-read to show whether a post has been read or not, per-user. In PHP, my plugin keeps track of this depending on page views while logged in.

I’m now trying to add a front-end AJAX control to let users manually set a post as “unread” or “read”. I’ve read that the WordPress REST API comes with a JavaScript library for interacting with it, and this is bundled with WordPress too. According to the documentation, this also handles authentication and noncing transparently, and one must simply extend a base class:

For developers using the built-in Javascript API, this is handled
automatically for you. This is the recommended way to use the API for
plugins and themes. Custom data models can extend wp.api.models.Base
to ensure this is sent correctly for any custom requests.

I’d like to use this so I don’t have to deal with nonces. I’ve found an example how to use the library with the built-in post model, but I want to extend this for my custom endpoint.

I want to know whether it’s appropriate to use and extend this library for sending POST requests, and if so, how I extend wp.api.models.Base to support this simple endpoint. All the examples I’ve found are for built-in objects like post, taxonomy, etc.

Read more here:: Extending wp JavaScript base class to make a post request to a custom REST endpoint

Leave a Reply

Your email address will not be published. Required fields are marked *