Add custom WordPress REST API endpoints
The addition of the WordPress REST API has turned WordPress into a CMS that can be used in headless websites and applications. Developers who are already comfortable using WordPress to store their content can now easily access it from anywhere.
There are a number of built-in routes available in the WordPress REST API to pull out the standard data types. It’s also possible to create and define custom REST API endpoints to return whatever data we want.
In this example we’re going to create an endpoint that returns the current date. The first thing to do is define the new route using the rest_api_init
action. We’ll have two endpoints to get the current date and current year.
WordPress provides an action called rest_api_init
which is used to initialise custom REST API endpoints.
The action calls the register_rest_route
function which creates the route using the arguments passed in. The first two arguments are the namespace and the route which make up the endpoint. Then we have an array of options which specifies exactly what should be done when this endpoint is queried.
For this endpoint, when the year is queried we want the API method to be a GET, and then we specify a function called get_date()
to run when the endpoint is queried, and in that function we’ll simply return the current date in an array.
If you save this to functions.php
and load http://example.com/wp-json/date/v1/date
in a browser, change example.com to the location of your WordPress installation, you will see the date output as a JSON object.
To set up the endpoint to return just the year we can create a similar function and just change the route and callback function to return just the year from the current date.
In our examples above we’ve only created simple callback functions, but these can be as complex as you’d like. In the past I’ve created a callback that retrieves data from the database to return when an endpoint is queried.
The endpoints you create can be used by other functions on the WordPress site itself or by other applications or websites.