SuperAPI AI 工具集

wp-rest-api

编程与开发

查看项目

更新于 10-16 03:17

技能介绍

用途:在 WordPress 中构建 REST API 端点、自定义路由、控制器,或使用 Abilities API 时参考。

主要能力:在 rest_api_init 钩子上用 register_rest_route() 注册路由,复杂端点可继承 WP_REST_Controller 实现 CRUD;命名空间须用 vendor/v1,不得使用 wp/*;提供 HTTP 方法常量(READABLE、CREATABLE、EDITABLE、DELETABLE、ALLMETHODS)。使用 JSON Schema(draft 4 子集)做资源定义与参数校验,通过 get_item_schema() 或 schema 回调提供,OPTIONS 请求可返回 schema 供发现。支持 validate_callback 与 sanitize_callback,注意覆盖 sanitize_callback 后内置校验不再自动运行,需用 rest_validate_request_arg 保留。

权限与认证:每个路由必须有 permission_callback,公开读用 __return_true,写端点须用 current_user_can() 检查能力;敏感端点可设 show_in_index => false。认证方式包括 Cookie + nonce(X-WP-Nonce)、应用密码(Basic Auth,需 HTTPS)、OAuth/JWT 插件,以及 rest_authentication_errors 过滤器。

响应与扩展:用 WP_REST_Response 或 rest_ensure_response() 返回,可加 X-WP-Total、X-WP-TotalPages 分页头;register_rest_field() 添加计算字段,register_meta() 暴露元数据;支持 _fields 稀疏响应、_embed、_envelope、_jsonp、_method 等全局参数及 batch/v1 批量请求。自定义文章类型与分类法需 show_in_rest => true 并设 rest_base。

Abilities API(WordPress 6.9+):先在 wp_abilities_api_categories_init 注册分类,再在 wp_abilities_api_init 注册能力,设 meta.show_in_rest => true 后经 GET /wp-json/wp-abilities/v1/abilities 暴露,客户端用 @wordpress/abilities。

错误处理:返回 WP_Error 并在 data 中带 status(400/401/403/404/500),不要在回调中调用 wp_send_json() 或 die()。

限制:per_page 上限 100;不得删除或修改核心字段;读取参数应使用 $request->get_param() 而非直接读 $_GET/$_POST。资料未提供具体版本兼容范围与性能数据。