Some people think I’m crazy for trying an advent calendar again, since I already have so little time for things as it is. But since I’ve barely blogged this year and then came up with a good idea for a themed advent calendar, I’m giving it another try. As I write this, it’s only November 21, so I have a few days to get a head start this year.
But now you’re probably wondering what theme I’ve chosen this year. Well, the title might already give it away. Over the next 24 days, I’ll be exploring 24 different APIs in WordPress. Not all of them are as “obvious” as the REST API, but many features you use regularly in WordPress are APIs in one way or another.
I’ll try to keep the structure of all the blog posts as consistent as possible so you can get to know each API in the same way. So let’s get started with the first blog post of the WordPress API advent calendar.
What does the REST API do?
The REST API makes your WordPress site accessible from the outside via HTTP requests. In response, you receive a JSON object. In the past, you often had to define your own AJAX endpoint for something like this – I’ve done that a lot and wrote some blog posts about it. But today, the REST API is a much more elegant solution.
The “client” can be a browser – for example, the Block Editor sends many requests to the REST API. But it can also be a JavaScript frontend in a “headless” system. Or it could be an app, another service, or a server. Almost every bigger service offers a REST API, and every WordPress installation has had one since WordPress 4.7. The initial release included endpoints for posts, pages, media, users, and more. Over time, many more were added.
Before we create our own endpoints, here are two more terms you should know:
- A “route” is the URL, for example,
/advent-calendar/v1/post/42. - An “endpoint” is the combination of a route and an HTTP method.
GETandPOSTrequests to the same route are two endpoints.
By default, all routes are located at https://example.com/wp-json/, followed by the respective route.
Which functions should I know?
If we want to create our own route, we use the register_rest_route() function. With this function, we specify the URL under which our endpoint can be accessed and what happens next with the request. The function is defined as follows:
register_rest_route(
string $route_namespace,
string $route,
array $args = [],
bool $override = false
): bool
For the namespace, you typically use the vendor/version scheme. So, for example, if we want to create an endpoint for our Advent calendar, we could use advent-calendar/v1. The route can also be configured with parameters. Using a named group such as (?P<id>\d+), for example, we can pass the ID of a post and retrieve this value later. Through the $args array, we can specify which HTTP method to use, which callback function to call, who is allowed to access the endpoint, and much more.
The function should only be called in the rest_api_init hook and not, for example, in plugins_loaded, which is often used in plugins.
In your callback function, you can then access a WP_REST_Request object and retrieve the previously passed post ID using, for example, $request->get_param( 'id' ) or $request['id']. It doesn’t matter whether the ID is in the URL, in a query string, or in the body. It’s best to return your data using rest_ensure_response(). This function wraps it in a WP_REST_Response object. An echo, on the other hand, has no place in the callback.
What does this look like in practice?
Let’s build a small practical example for our Advent calendar endpoint. The desired URL is /wp-json/advent-calendar/v1/post/<id>, and the complete definition might look like this:
<?php
/**
* Plugin Name: Advent Calendar – REST API
* Description: A custom REST endpoint for the advent calendar.
* Text Domain: advent-calendar
*/
function advent_calendar_register_routes() {
register_rest_route(
'advent-calendar/v1',
'/post/(?P<id>\d+)',
[
'methods' => WP_REST_Server::READABLE,
'callback' => 'advent_calendar_get_post',
'permission_callback' => '__return_true',
'args' => [
'id' => [
'description' => __( 'The post ID.', 'advent-calendar' ),
'required' => true,
'validate_callback' => function ( $value ) {
return is_numeric( $value ) && (int) $value > 0;
},
'sanitize_callback' => 'absint',
],
],
]
);
}
add_action( 'rest_api_init', 'advent_calendar_register_routes' );
function advent_calendar_get_post( WP_REST_Request $request ) {
$post = get_post( $request->get_param( 'id' ) );
$is_visible = $post
&& 'post' === $post->post_type
&& is_post_publicly_viewable( $post )
&& ! post_password_required( $post )
&& has_tag( 'wordpress-api-adventskalender', $post );
if ( ! $is_visible ) {
return new WP_Error(
'advent_calendar_post_not_found',
__( 'Post not found.', 'advent-calendar' ),
[
'status' => 404,
]
);
}
$content = wp_strip_all_tags( $post->post_content );
return rest_ensure_response(
[
'id' => $post->ID,
'title' => get_the_title( $post ),
'link' => get_permalink( $post ),
'date' => get_post_time( 'c', true, $post ),
'excerpt' => wp_trim_words( $content, 30 ),
]
);
}
Key points:
We attach the registration to rest_api_init. This ensures that our route is only registered when WordPress initializes the REST API.
If the endpoint is publicly accessible – that is, without a login – we naturally want to be careful about which entries we return. That’s why we use is_post_publicly_viewable() to check whether the post is publicly visible at all. After all, we don’t want to accidentally deliver drafts or private posts via our API. However, the function does not recognize password-protected posts, since they normally have the “published” status. That’s why we also exclude them using post_password_required(); otherwise, anyone without a password could read the beginning of the protected content in the excerpt. All non-public posts return the same 404 response as unknown IDs. And finally, we use has_tag() to filter by a tag so that only posts from this Advent calendar are returned.
The two callbacks, validate_callback and sanitize_callback, run before the actual request callback. The validation rejects invalid values with an error, while the sanitization converts valid values to integers.
Of course, we make the parameter description and the error message translatable using __().
We can test the endpoint directly from the command line:
curl https://example.com/wp-json/advent-calendar/v1/post/42
What should I watch out for?
One thing you should never forget when creating your own REST endpoints is the permission_callback. WordPress expects this function for every endpoint. Since WordPress 5.5, we get at least a _doing_it_wrong() notice if we leave it out.
Here, we simply use __return_true, so we don’t check further to see if the request requires specific permissions. For example, if we only want to allow requests from users who can edit posts, we would use something like current_user_can( 'edit_posts' ) here. Apart from this “access control,” however, we still need to ensure that we return only the data that is necessary.
By the way, authentication doesn’t happen automatically. The check with current_user_can() only helps if WordPress knows who’s making the request. For a request from the frontend, this is handled via the login cookie plus a wp_rest nonce in the X-WP-Nonce header. For external applications, it’s best to use “application passwords” and create a dedicated “REST user” for this purpose. If you were to use an “application password” from your own user account, requests could – in the worst-case scenario – be granted admin privileges and access information you’d rather not expose externally.
Also, be careful how you validate the $args. You should not use PHP functions like is_numeric directly as a validate_callback; instead, always use them within a closure. WordPress passes multiple arguments to the callback function, which can trigger warnings with internal PHP functions if they only expect a single parameter.
And as mentioned earlier, it’s important to always return data rather than output it. An echo or wp_send_json() should never be used in a REST callback.
If you want to return errors, always include a status code. A WP_Error without a status will be returned to the client as a 500. For example, use 404 for “not found” and 401 or 403 for insufficient permissions.
When should I use it?
A dedicated REST endpoint always makes sense when other applications need to access specific data from our plugin. As mentioned earlier, this could be the Block Editor, a custom JavaScript frontend, an app, or even an external service.
However, we don’t need to build a separate endpoint for every little thing. For example, if we just want to make an additional field available for a post via the REST API, register_rest_field() or register_meta() in combination with show_in_rest is perfectly sufficient. If you’ve created your own post types, they’ll automatically be equipped with complete endpoints when you set 'show_in_rest' => true. That’s another reason why I prefer to use a custom post type rather than creating my own objects and tables. For a complete resource with all CRUD functions (read, create, update, and delete), it might be worth creating your own class based on WP_REST_Controller.
Where can I find more information?
- REST API Handbook
- Adding Custom Endpoints
- Routes and Endpoints
- Controller Classes
- Authentication
- Code Reference:
register_rest_route() - Code Reference:
rest_ensure_response() - Code Reference:
WP_REST_Request
What should I remember?
- We can interact with WordPress via HTTP using the REST API. We can create our own endpoints using
register_rest_route()in therest_api_inithook. - For each endpoint, consider who should be allowed to access it. Even public endpoints require a
permission_callback. - Check the parameters passed in and return your data cleanly. If something does go wrong, a
WP_Errorobject with an appropriate status code can help us troubleshoot.
And that’s it for the first API. As befits a good advent calendar, I’m not going to tell you what to expect tomorrow, of course. 😀
