我正在为REST API集成(WP 4.7核心版本)准备一个插件,为插件中的数据提供自定义端点。我想做的一件事就是_links
属性,并使链接的资源可嵌入。高度简化的代码摘录:
class Clgs_REST_Logs extends WP_REST_Controller {
const NSPACE = \'clgs\';
const BASE = \'logs\';
public function register_routes() {
register_rest_route( self::NSPACE, \'/\' . self::BASE, array(
array(
\'methods\' => WP_REST_Server::READABLE,
\'callback\' => array( $this, \'get_items\' ),
),
\'schema\' => array( $this, \'get_public_item_schema\' ),
) );
register_rest_route( self::NSPACE, \'/\' . self::BASE . \'/count\', array(
array(
\'methods\' => WP_REST_Server::READABLE,
\'callback\' => array( $this, \'get_count\' ),
),
\'schema\' => array( $this, \'get_count_schema\' ),
) );
}
public function get_items( $request ) {
$log_entries = // get an array
$collection = $this->prepare_collection_for_response( $log_entries, $request );
$response = rest_ensure_response( array(
\'items\' => $collection
) );
$max_pages = max( 1, ceil( $total_items / (int) $params[\'per_page\'] ) );
$this->set_count_headers( $response, (int) $total_items, (int) $max_pages );
$count_link = $this->prepare_link_url( array( self::BASE, \'count\' ) );
$response->add_links( array (
\'count\' => array(
\'href\' => $count_link,
\'embeddable\' => true
),
) );
return $response;
}
public function get_count( $request ) {
// provide some statistics data
}
public function prepare_link_url ( $parts = array() ) {
array_unshift( $parts, self::NSPACE );
return rest_url( implode( \'/\', $parts ) . \'/\' );
}
}
对请求的响应
http://wptesting.intern/index.php/wp-json/clgs/logs/?_embed
如下所示:
{
"items": [...],
"_links": {
"count": [{
"embeddable": true,
"href": "http://wptesting.intern/index.php/wp-json/clgs/logs/"
}]
},
"_embedded": {
"count": [{
"code": "rest_no_route",
"message": "No route was found matching the URL and request method",
"data": {"status":404}
}]
}
}
请求发送至
http://wptesting.intern/index.php/wp-json/clgs/logs/count/
, 如果单独执行,则成功。
我在禁用了premalinks和http://wptesting.intern/index.php/?route=...
要确保这不是路由重写问题,同样的情况也会发生。
有人知道嵌入失败的原因吗?