rest_api_init
Fires when the REST API is being set up. Register your own REST routes and fields here with register_rest_route().
When it fires
rest_api_init runs when WordPress sets up the REST server, which normally happens only for REST API requests (URLs under /wp-json/). Registering routes here rather than on init means the work is only done when it's needed.
It can also fire during other requests when code calls rest_do_request(), for example when the block editor preloads data.
Parameters
$wp_rest_serverWP_REST_Server |
Server object. |
|---|
Example: Add a read-only endpoint for the latest post
add_action( 'rest_api_init', function () {
register_rest_route(
'my-snippets/v1',
'/latest-post',
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => '__return_true',
'callback' => function () {
$posts = get_posts( array( 'numberposts' => 1 ) );
if ( ! $posts ) {
return new WP_Error( 'no_posts', __( 'No posts found.', 'my-snippets' ), array( 'status' => 404 ) );
}
return array(
'title' => get_the_title( $posts[0] ),
'link' => get_permalink( $posts[0] ),
);
},
)
);
} );
Good to know
- Always set permission_callback. Use '__return_true' only for public, read-only data, and a current_user_can() check for anything else.
- Use your own namespace with a version, such as 'my-snippets/v1', so your routes don't clash with anyone else's.
- Try it at /wp-json/my-snippets/v1/latest-post, or at /?rest_route=/my-snippets/v1/latest-post if pretty permalinks are off.