How to create a custom WordPress Rest Api route.

The WordPress Rest Api has many build in endpoints for you to access. But sometimes you may need something a little more specific, or need access to a resource that is not supported out of the box. In these cases you can create your own custom endpoint. In this example we create a (pretty useless) endpoint for fetching post meta values.

With the snippet above we add an action to the rest_api_init hook, and register a new callback function called mytheme_get_meta_value.

With the mytheme_get_meta_value function we make a call to the register_rest_route function and pass three parameters:

  • $namespace: A unique namespace that groups your custom endpoints. This will be the first URL segment after core prefix. (/wp-json/your-namespace/resource/param/param)
  • $route: The actual route. Usually a resource name with optional parameters. (/wp-json/your-namespace/resource/param/param)
  • $args: An array of arguments.

For the $route parameter we pass a string including two parameter expressions like (?P<post>[\d]+) This tells WordPress that we are expecting a parameter (?P) by the name of “post” with a value that must follow the regular expression of [\d]+ meaning an integer/id. Second we expect a parameter by the name of “key” that must follow the regular expression of [a-zA-Z0-9_-]+ meaning a string of letters, numbers. underscores and dashes.

Note: You don’t have to use url parameters in this way. You can also pass Get parameters (?posts=9&key=some_value) or Post parameters.

For the arguments parameter we pass an array with two key/value pairs:

  • Methods: The request method. E.g. GET, POST or a WP_REST_Server constant like
    WP_REST_Server::READABLE = ‘GET’,
    WP_REST_Server::EDITABLE = ‘POST, PUT, PATCH’,
    WP_REST_Server::DELETABLE = ‘DELETE’,
    WP_REST_Server::ALLMETHODS = ‘GET, POST, PUT, PATCH, DELETE’
  • Callback: The callback function that will be called when the route is requested.

Note: You could also pass an array of arrays where each inner array has a different method and callback function. This is useful when you need a different callback function for Get and Post methods.

End-point callback function.

In the code above we passed mytheme_handle_get_meta_value as our route callback function. Lets create that function now.

In this callback function we first extract the post and key parameters from the passed in $request array. These values come from the Url parameters we set for the $route parameter in the register_rest_route function earlier.

We then use these values to retrieve the meta value using the get_post_meta function. If the value can not be found we return a WP_Error object explaining what went wrong. If we did find a value we use the rest_ensure_response function to return it. The rest_ensure_response function expects an array so we create one with a key of meta and the value we need to return. We use the meta key in our javascript later to retrieve the value.

Calling the End-point with Javascript

Now that our endpoint is set up, we can try and call it using Javascript.

Here we use the $.ajax function to make a GET request to ‘/wp-jsaon/mytheme/v1/meta/9/_thumbnail_id’, where 9 is a post id and _thumbnail_id is the meta value we want to retrieve. On success we get the meta key from the returned data object to get our meta value and log it to the console. This meta key comes from the array we passed to rest_ensure_response earlier. If we get an error we use error.responseJSON.message to get the error message and log that to the console.

Further reading

This is just a simple/basic example and we didn’t handle things like securing the endpoint which I highly recommend you do when dealing with delicate data. You can read up on security and more in the Rest Api handbook under Adding custom endpoints.

Comments?

If you want to leave a comment, please do so under the copy of this article on Dev.to so i can get back to you.

Follow me on twitter @Vanaf1979 or Dev.to @Vanaf1979 or subscribe to my newsletter to be notified about new articles, and other WordPress development related resources.

Thanks for reading