用途:在 WordPress 中创建或更新 REST 路由与端点,调试 401/403/404 及权限/nonce 问题,为 REST 响应添加自定义字段或 meta,通过 REST 暴露自定义文章类型与分类法,实现 schema 与参数校验,调整响应链接、嵌入与分页。
主要能力:区分两种做法——用 show_in_rest => true(必要时配 rest_base、rest_controller_class)把 CPT/分类法暴露到 wp/v2;或在 rest_api_init 上用 register_rest_route() 注册自定义端点,非简单场景建议用 WP_REST_Controller 子类。注册时使用唯一命名空间 vendor/v1,始终提供 permission_callback(公开端点用 __return_true),用 WP_REST_Server 常量声明方法,通过 rest_ensure_response()/WP_REST_Response 返回数据,用带明确状态码的 WP_Error 返回错误。参数需定义 type、default、required、validate_callback、sanitize_callback,优先用 rest_validate_value_from_schema 与 rest_sanitize_value_from_schema 做 JSON Schema 校验,端点内不要直接读 $_GET/$_POST,改用 WP_REST_Request。响应方面不要删除核心字段,用 register_rest_field 加计算字段、register_meta 配 show_in_rest 加 meta,对象/数组 meta 需在 show_in_rest.schema 定义 schema;需要未过滤内容时用 ?context=edit 取 content.raw(需认证),可配 _fields=content.raw 减小响应;用 WP_REST_Response::add_link() 加关联链接。认证上,wp-admin/JS 用 cookie + X-WP-Nonce(action 为 wp_rest),外部客户端用应用密码或认证插件,permission_callback 中做能力检查而非仅判断登录。客户端行为需保证发现机制(Link 头或 link rel),支持 _fields、_embed、_method、_envelope 与分页头,注意 per_page 上限为 100。
使用方式:先运行 node skills/wp-project-triage/scripts/detect_wp_project.mjs 做项目识别,并搜索 register_rest_route、WP_REST_Controller、rest_api_init、show_in_rest 等现有用法;全站仓库需先选定具体插件/主题。验证时检查 /wp-json/ 索引是否含命名空间、OPTIONS 是否返回 schema、权限失败是否返回 401/403、CPT/分类法路由是否出现在 wp/v2 下,并运行仓库 lint/测试与构建。
限制与调试:404 常因 rest_api_init 未触发、路由拼写错误或固定链接关闭(可用 ?rest_route=);401/403 多为缺少 nonce/认证或 permission_callback 过严;缺少 permission_callback 会触发 _doing_it_wrong;参数无效多为 args schema 或校验回调缺失;字段缺失常因 show_in_rest 为 false、meta 未注册或 CPT 不支持自定义字段。版本支持或行为不明确时,应先查阅 REST API Handbook 与核心文档。