The WordPress REST API is a strong replacement for the admin-ajax API in core. It lets you structure the
way data goes into and out of WordPress instead of routing everything through a single action parameter,
which usually means less plumbing code and cleaner AJAX calls.
Routes and endpoints
A route is the URI that can be matched to different HTTP methods (GET, POST, DELETE and so on).
The mapping of an individual HTTP method to a route is known as an endpoint. In other words, “route” refers to the URL, whereas “endpoint” refers to the function behind it that corresponds to a particular method on that URL.
To see all registered routes and endpoints of a site:
// With pretty permalinks:
http://oursite.com/wp-json/
// Otherwise:
http://oursite.com/?rest_route=/
Registering a route
Routes are registered on the rest_api_init hook:
add_action( 'rest_api_init', function () {
register_rest_route( 'shops-script/v1', '/update', [
'methods' => 'POST',
'callback' => 'my_function',
] );
} );
The first argument is the namespace — always prefix it with your plugin or project name to avoid collisions with other extensions.
Reading parameters
The callback receives a WP_REST_Request object:
function my_awesome_func( WP_REST_Request $request ) {
// Parameters are accessible via direct array access on the object:
$param = $request['some_param'];
// Or via the helper method:
$param = $request->get_param( 'some_param' );
// The combined, merged set of parameters:
$parameters = $request->get_params();
// The individual sets of parameters are also available, if needed:
$parameters = $request->get_url_params();
$parameters = $request->get_query_params();
$parameters = $request->get_body_params();
$parameters = $request->get_json_params();
$parameters = $request->get_default_params();
// Uploads aren't merged in, but can be accessed separately:
$parameters = $request->get_file_params();
}
If the request has the Content-Type: application/json header set and a valid JSON body,
get_json_params() returns the parsed body as an associative array.
Andrew Dorokhov