How to add an endpoint to the WordPress REST API

Adding an endpoint to the WordPress REST API opens a lot of possibilities for you as a developer. For example, if you want to work with the data stored in your WordPress website and want to transfer it in some way you can select exactly the data you need, publish it with the webservice and consume it somewhere else. Let’s have a look at how to set this up.

Adding the endpoint

Add your own plugin to WordPress, activate it and make sure to include the following code to setup the webservice endpoint. All you have to do is to declare a function that returns the result you want to publish with the webservice. The data is automatically encoded in JSON by WordPress itself and you do not have to worry about it here.

Then register your method with the register_rest_route function call and provide the URL path split up in a namespace and route part and an arguments array that holds a reference to your special function. In this example we register the my_post_ws_endpoint_get function under the my-posts/v1/get path for a HTTP Get request.

The webservice client

The webservice client part can request the data with the wp_remote_get function. The method call returns a wrapper for the HTTP request and the body element of the array holds the JSON encoded string. You can then use the json_decode function to deserialize the data back to a PHP array for example or whatever datatype your webservice returned and work with the data.


It is pretty easy to add an endpoint to the WordPress REST API and this opens a world full of possible new use cases. Have a look at the really excellent documentation on for more detailed information.