-
StackOverflow 文件
-
WordPress 教程
-
REST API
-
完整的工作示例
add_action('rest_api_init', 'my_rest_validate_endpoint' );
function my_rest_validate_endpoint() {
// Declare our namespace
$namespace = 'myrest/v1';
// Register the route
// Example URL matching this route:
// http://yourdomain/wp-json/myrest/v1/guides/tag=europe/price=29
register_rest_route($namespace,
// Using regular expressions we can initially validate the input
'/guides/tag=(?P<tag>[a-zA-Z0-9-]+)/price=(?P<price>[0-9]+)',
// We can have multiple endpoints for one route
array(
array(
'methods' => 'GET',
'callback' => 'my_get_guides_handler'
)
),
// We can register our schema callback
// 'schema' => 'my_get_guide_schema',
);
// You can register another route here the same way
}
// The callback handler for the endpoint
function my_get_guides_handler(WP_REST_Request $request) {
// Get the parameters:
$tag = $request->get_param('tag');
$price = $request->get_param('price');
// Do something with the parameters
// for instance: get matching guides from the DB into an array - $results
// ...
// Prepare the response
$message = "We've found " . count($results) . " guides ";
$message .= "(searching for a tag: " . $tag . ", with a price tag: " . $price . ")";
// The response gets automatically converted into a JSON format
return new WP_REST_Response(
array(
'results' => $results,
'message' => $message,
'status' => 'OK'
),
200 );
}