wp-rest-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

WP REST API

WP REST API

When to use

适用场景

Use this skill when you need to:
  • create or update REST routes/endpoints
  • debug 401/403/404 errors or permission/nonce issues
  • add custom fields/meta to REST responses
  • expose custom post types or taxonomies via REST
  • implement schema + argument validation
  • adjust response links/embedding/pagination
当你需要以下操作时,可使用本技能:
  • 创建或更新REST路由/端点
  • 调试401/403/404错误或权限/nonce问题
  • 为REST响应添加自定义字段/元数据
  • 通过REST暴露自定义文章类型或分类法
  • 实现Schema + 参数验证
  • 调整响应链接/嵌入/分页

Inputs required

所需输入

  • Repo root + target plugin/theme/mu-plugin (path to entrypoint).
  • Desired namespace + version (e.g.
    my-plugin/v1
    ) and routes.
  • Authentication mode (cookie + nonce vs application passwords vs auth plugin).
  • Target WordPress version constraints (if below 6.9, call out).
  • 仓库根目录 + 目标插件/主题/mu-plugin(入口文件路径)。
  • 所需的命名空间 + 版本(例如
    my-plugin/v1
    )以及路由。
  • 身份验证模式(Cookie + Nonce vs 应用密码 vs 身份验证插件)。
  • 目标WordPress版本限制(如果低于6.9,请特别说明)。

Procedure

操作步骤

0) Triage and locate REST usage

0) 问题排查与REST用法定位

  1. Run triage:
    • node skills/wp-project-triage/scripts/detect_wp_project.mjs
  2. Search for existing REST usage:
    • register_rest_route
    • WP_REST_Controller
    • rest_api_init
    • show_in_rest
      ,
      rest_base
      ,
      rest_controller_class
If this is a full site repo, pick the specific plugin/theme before changing code.
  1. 运行排查脚本:
    • node skills/wp-project-triage/scripts/detect_wp_project.mjs
  2. 搜索现有的REST用法:
    • register_rest_route
    • WP_REST_Controller
    • rest_api_init
    • show_in_rest
      ,
      rest_base
      ,
      rest_controller_class
如果是完整站点仓库,请在修改代码前选择特定的插件/主题。

1) Choose the right approach

1) 选择合适的实现方式

  • Expose CPT/taxonomy in
    wp/v2
    :
    • Use
      show_in_rest => true
      +
      rest_base
      if needed.
    • Optionally provide
      rest_controller_class
      .
    • Read
      references/custom-content-types.md
      .
  • Custom endpoints:
    • Use
      register_rest_route()
      on
      rest_api_init
      .
    • Prefer a controller class (
      WP_REST_Controller
      subclass) for anything non-trivial.
    • Read
      references/routes-and-endpoints.md
      and
      references/schema.md
      .
  • wp/v2
    中暴露自定义文章类型/分类法:
    • 若需要,使用
      show_in_rest => true
      +
      rest_base
    • 可选择性提供
      rest_controller_class
    • 阅读
      references/custom-content-types.md
  • 自定义端点:
    • rest_api_init
      钩子上使用
      register_rest_route()
    • 对于非简单功能,优先使用控制器类(
      WP_REST_Controller
      的子类)。
    • 阅读
      references/routes-and-endpoints.md
      references/schema.md

2) Register routes safely (namespaces, methods, permissions)

2) 安全注册路由(命名空间、方法、权限)

  • Use a unique namespace
    vendor/v1
    ; avoid
    wp/*
    unless core.
  • Always provide
    permission_callback
    (use
    __return_true
    for public endpoints).
  • Use
    WP_REST_Server::READABLE/CREATABLE/EDITABLE/DELETABLE
    constants.
  • Return data via
    rest_ensure_response()
    or
    WP_REST_Response
    .
  • Return errors via
    WP_Error
    with an explicit
    status
    .
Read
references/routes-and-endpoints.md
.
  • 使用唯一的命名空间
    vendor/v1
    ;除非是核心功能,否则避免使用
    wp/*
  • 务必提供
    permission_callback
    (公开端点可使用
    __return_true
    )。
  • 使用
    WP_REST_Server::READABLE/CREATABLE/EDITABLE/DELETABLE
    常量。
  • 通过
    rest_ensure_response()
    WP_REST_Response
    返回数据。
  • 通过带有明确
    status
    WP_Error
    返回错误信息。
阅读
references/routes-and-endpoints.md

3) Validate/sanitize request args

3) 验证与清理请求参数

  • Define
    args
    with
    type
    ,
    default
    ,
    required
    ,
    validate_callback
    ,
    sanitize_callback
    .
  • Prefer JSON Schema validation with
    rest_validate_value_from_schema
    then
    rest_sanitize_value_from_schema
    .
  • Never read
    $_GET
    /
    $_POST
    directly inside endpoints; use
    WP_REST_Request
    .
Read
references/schema.md
.
  • 定义包含
    type
    default
    required
    validate_callback
    sanitize_callback
    args
  • 优先使用JSON Schema验证,结合
    rest_validate_value_from_schema
    rest_sanitize_value_from_schema
  • 切勿在端点内直接读取
    $_GET
    /
    $_POST
    ;请使用
    WP_REST_Request
阅读
references/schema.md

4) Responses, fields, and links

4) 响应、字段与链接

  • Do not remove core fields from default endpoints; add fields instead.
  • Use
    register_rest_field
    for computed fields;
    register_meta
    with
    show_in_rest
    for meta.
  • For
    object
    /
    array
    meta, define schema in
    show_in_rest.schema
    .
  • If you need unfiltered post content (e.g., ToC plugins injecting HTML), request
    ?context=edit
    to access
    content.raw
    (auth required). Pair with
    _fields=content.raw
    to keep responses small.
  • Add related resource links via
    WP_REST_Response::add_link()
    .
Read
references/responses-and-fields.md
.
  • 不要从默认端点中移除核心字段;应添加字段而非删除。
  • 对于计算字段,使用
    register_rest_field
    ;对于元数据,使用带有
    show_in_rest
    register_meta
  • 对于
    object
    /
    array
    类型的元数据,在
    show_in_rest.schema
    中定义Schema。
  • 如果需要未过滤的文章内容(例如,目录插件注入HTML),请求时携带
    ?context=edit
    以访问
    content.raw
    (需要身份验证)。可搭配
    _fields=content.raw
    来缩小响应体积。
  • 通过
    WP_REST_Response::add_link()
    添加相关资源链接。
阅读
references/responses-and-fields.md

5) Authentication and authorization

5) 身份验证与授权

  • For wp-admin/JS: cookie auth +
    X-WP-Nonce
    (action
    wp_rest
    ).
  • For external clients: application passwords (basic auth) or an auth plugin.
  • Use capability checks in
    permission_callback
    (authorization), not just “logged in”.
Read
references/authentication.md
.
  • 对于wp-admin/JS:Cookie认证 +
    X-WP-Nonce
    (动作
    wp_rest
    )。
  • 对于外部客户端:应用密码(基础认证)或身份验证插件。
  • permission_callback
    中使用权限检查(授权),而不只是检查“是否登录”。
阅读
references/authentication.md

6) Client-facing behavior (discovery, pagination, embeds)

6) 客户端行为(发现、分页、嵌入)

  • Ensure discovery works (
    Link
    header or
    <link rel="https://api.w.org/">
    ).
  • Support
    _fields
    ,
    _embed
    ,
    _method
    ,
    _envelope
    , pagination headers.
  • Remember
    per_page
    is capped at 100.
Read
references/discovery-and-params.md
.
  • 确保发现功能正常工作(
    Link
    头或
    <link rel="https://api.w.org/">
    )。
  • 支持
    _fields
    _embed
    _method
    _envelope
    、分页头。
  • 注意
    per_page
    的上限为100。
阅读
references/discovery-and-params.md

Verification

验证步骤

  • /wp-json/
    index includes your namespace.
  • OPTIONS
    on your route returns schema (when provided).
  • Endpoint returns expected data; permission failures return 401/403 as appropriate.
  • CPT/taxonomy routes appear under
    wp/v2
    when
    show_in_rest
    is true.
  • Run repo lint/tests and any PHP/JS build steps.
  • /wp-json/
    索引中包含你的命名空间。
  • 对路由发送
    OPTIONS
    请求时返回Schema(如果已提供)。
  • 端点返回预期数据;权限验证失败时返回正确的401/403状态码。
  • show_in_rest
    设为true时,自定义文章类型/分类法路由出现在
    wp/v2
    下。
  • 运行仓库的代码检查/测试,以及任何PHP/JS构建步骤。

Failure modes / debugging

故障模式与调试

  • 404:
    rest_api_init
    not firing, route typo, or permalinks off (use
    ?rest_route=
    ).
  • 401/403: missing nonce/auth, or
    permission_callback
    too strict.
  • _doing_it_wrong
    for missing
    permission_callback
    : add it (use
    __return_true
    if public).
  • Invalid params: missing/incorrect
    args
    schema or validation callbacks.
  • Fields missing:
    show_in_rest
    false, meta not registered, or CPT lacks
    custom-fields
    support.
  • 404错误:
    rest_api_init
    未触发、路由拼写错误,或固定链接未开启(可使用
    ?rest_route=
    )。
  • 401/403错误:缺少nonce/身份验证,或
    permission_callback
    过于严格。
  • 因缺少
    permission_callback
    触发
    _doing_it_wrong
    :添加该回调(公开端点可使用
    __return_true
    )。
  • 参数无效:缺少/错误的
    args
    Schema或验证回调。
  • 字段缺失:
    show_in_rest
    设为false、元数据未注册,或自定义文章类型不支持
    custom-fields

Escalation

升级处理

If version support or behavior is unclear, consult the REST API Handbook and core docs before inventing patterns.
如果版本支持或行为不明确,请先查阅REST API手册和核心文档,不要自行创造实现模式。