wp-interactivity-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

WP Interactivity API

WordPress Interactivity API

When to use

使用场景

Use this skill when the user mentions:
  • Interactivity API,
    @wordpress/interactivity
    ,
  • data-wp-interactive
    ,
    data-wp-on--*
    ,
    data-wp-bind--*
    ,
    data-wp-context
    ,
  • block
    viewScriptModule
    / module-based view scripts,
  • hydration issues or “directives don’t fire”.
当用户提及以下内容时,可使用本技能:
  • Interactivity API、
    @wordpress/interactivity
  • data-wp-interactive
    data-wp-on--*
    data-wp-bind--*
    data-wp-context
  • 区块
    viewScriptModule
    / 基于模块的视图脚本,
  • hydration问题或“指令未触发”问题。

Inputs required

所需输入

  • Repo root + triage output (
    wp-project-triage
    ).
  • Which block/theme/plugin surfaces are affected (frontend, editor, both).
  • Any constraints: WP version, whether modules are supported in the build.
  • 代码库根目录 + 分类输出(
    wp-project-triage
    )。
  • 受影响的区块/主题/插件范围(前端、编辑器、或两者均受影响)。
  • 任何限制条件:WordPress版本、构建是否支持模块。

Procedure

操作步骤

1) Detect existing usage + integration style

1) 检测现有使用方式与集成风格

Search for:
  • data-wp-interactive
  • @wordpress/interactivity
  • viewScriptModule
Decide:
  • Is this a block providing interactivity via
    block.json
    view script module?
  • Is this theme-level interactivity?
  • Is this plugin-side “enhance existing markup” usage?
If you’re creating a new interactive block (not just debugging), prefer the official scaffold template:
  • @wordpress/create-block-interactive-template
    (via
    @wordpress/create-block
    )
搜索以下内容:
  • data-wp-interactive
  • @wordpress/interactivity
  • viewScriptModule
判断:
  • 是否为通过
    block.json
    视图脚本模块提供交互性的区块?
  • 是否为主题级别的交互性?
  • 是否为插件端“增强现有标记”的使用场景?
如果您要创建新的交互式区块(而非仅调试),建议使用官方脚手架模板:
  • @wordpress/create-block-interactive-template
    (通过
    @wordpress/create-block
    使用)

2) Identify the store(s)

2) 识别存储(Store)

Locate store definitions and confirm:
  • state shape,
  • actions (mutations),
  • callbacks/event handlers used by
    data-wp-on--*
    .
定位存储定义并确认:
  • 状态结构,
  • 动作(变更),
  • data-wp-on--*
    所使用的回调/事件处理器。

3) Server-side rendering (best practice)

3) 服务器端渲染(最佳实践)

Pre-render HTML on the server before outputting to ensure:
  • Correct initial state in the HTML before JavaScript loads (no layout shift).
  • SEO benefits and faster perceived load time.
  • Seamless hydration when the client-side JavaScript takes over.
在输出前在服务器端预渲染HTML,以确保:
  • JavaScript加载前,HTML中包含正确的初始状态(无布局偏移)。
  • 利于SEO,且感知加载速度更快。
  • 客户端JavaScript接管时实现无缝hydration。

Enable server directive processing

启用服务器端指令处理

For components using
block.json
, add
supports.interactivity
:
json
{
  "supports": {
    "interactivity": true
  }
}
For themes/plugins without
block.json
, use
wp_interactivity_process_directives()
to process directives.
对于使用
block.json
的组件,添加
supports.interactivity
json
{
  "supports": {
    "interactivity": true
  }
}
对于未使用
block.json
的主题/插件,使用
wp_interactivity_process_directives()
处理指令。

Initialize state/context in PHP

在PHP中初始化状态/上下文

Use
wp_interactivity_state()
to define initial global state:
php
wp_interactivity_state( 'myPlugin', array(
  'items'    => array( 'Apple', 'Banana', 'Cherry' ),
  'hasItems' => true,
));
For local context, use
wp_interactivity_data_wp_context()
:
php
<?php
$context = array( 'isOpen' => false );
?>
<div <?php echo wp_interactivity_data_wp_context( $context ); ?>>
  ...
</div>
使用
wp_interactivity_state()
定义初始全局状态:
php
wp_interactivity_state( 'myPlugin', array(
  'items'    => array( 'Apple', 'Banana', 'Cherry' ),
  'hasItems' => true,
));
对于本地上下文,使用
wp_interactivity_data_wp_context()
php
<?php
$context = array( 'isOpen' => false );
?>
<div <?php echo wp_interactivity_data_wp_context( $context ); ?>>
  ...
</div>

Define derived state in PHP

在PHP中定义派生状态

When derived state affects initial HTML rendering, replicate the logic in PHP:
php
wp_interactivity_state( 'myPlugin', array(
  'items'    => array( 'Apple', 'Banana' ),
  'hasItems' => function() {
    $state = wp_interactivity_state();
    return count( $state['items'] ) > 0;
  }
));
This ensures directives like
data-wp-bind--hidden="!state.hasItems"
render correctly on first load.
For detailed examples and patterns, see
references/server-side-rendering.md
.
当派生状态影响初始HTML渲染时,在PHP中复现该逻辑:
php
wp_interactivity_state( 'myPlugin', array(
  'items'    => array( 'Apple', 'Banana' ),
  'hasItems' => function() {
    $state = wp_interactivity_state();
    return count( $state['items'] ) > 0;
  }
));
这可确保
data-wp-bind--hidden="!state.hasItems"
等指令在首次加载时正确渲染。
有关详细示例和模式,请参阅
references/server-side-rendering.md

4) Implement or change directives safely

4) 安全实现或修改指令

When touching markup directives:
  • keep directive usage minimal and scoped,
  • prefer stable data attributes that map clearly to store state,
  • ensure server-rendered markup + client hydration align.
WordPress 6.9 changes:
  • data-wp-ignore
    is deprecated
    and will be removed in future versions. It broke context inheritance and caused issues with client-side navigation. Avoid using it.
  • Unique directive IDs: Multiple directives of the same type can now exist on one element using the
    ---
    separator (e.g.,
    data-wp-on--click---plugin-a="..."
    and
    data-wp-on--click---plugin-b="..."
    ).
  • New TypeScript types:
    AsyncAction<ReturnType>
    and
    TypeYield<T>
    help with async action typing.
For quick directive reminders, see
references/directives-quickref.md
.
处理标记指令时:
  • 尽量减少指令使用范围,保持作用域清晰,
  • 优先使用与存储状态清晰映射的稳定数据属性,
  • 确保服务器端渲染的标记与客户端hydration保持一致。
WordPress 6.9 变更:
  • data-wp-ignore
    已被弃用
    ,将在未来版本中移除。它会破坏上下文继承并导致客户端导航问题,请避免使用。
  • 唯一指令ID:现在可使用
    ---
    分隔符在单个元素上添加多个同类型指令(例如
    data-wp-on--click---plugin-a="..."
    data-wp-on--click---plugin-b="..."
    )。
  • 新增TypeScript类型
    AsyncAction<ReturnType>
    TypeYield<T>
    可帮助实现异步动作的类型定义。
如需快速查阅指令,请参阅
references/directives-quickref.md

5) Build/tooling alignment

5) 构建/工具对齐

Verify the repo supports the required module build path:
  • if it uses
    @wordpress/scripts
    , prefer its conventions.
  • if it uses custom bundling, confirm module output is supported.
验证代码库是否支持所需的模块构建路径:
  • 如果使用
    @wordpress/scripts
    ,请遵循其约定。
  • 如果使用自定义打包工具,请确认支持模块输出。

6) Debug common failure modes

6) 调试常见故障模式

If “nothing happens” on interaction:
  • confirm the
    viewScriptModule
    is enqueued/loaded,
  • confirm the DOM element has
    data-wp-interactive
    ,
  • confirm the store namespace matches the directive’s value,
  • confirm there are no JS errors before hydration.
See
references/debugging.md
.
如果交互时“无任何反应”:
  • 确认
    viewScriptModule
    已入队/加载,
  • 确认DOM元素包含
    data-wp-interactive
    属性,
  • 确认存储命名空间与指令值匹配,
  • 确认hydration前无JavaScript错误。
请参阅
references/debugging.md

Verification

验证

  • wp-project-triage
    indicates
    signals.usesInteractivityApi: true
    after your change (if applicable).
  • Manual smoke test: directive triggers and state updates as expected.
  • If tests exist: add/extend Playwright E2E around the interaction path.
  • 若相关,修改后
    wp-project-triage
    应显示
    signals.usesInteractivityApi: true
  • 手动冒烟测试:指令触发且状态按预期更新。
  • 若已有测试:围绕交互路径添加/扩展Playwright端到端测试。

Failure modes / debugging

故障模式/调试

  • Directives present but inert:
    • view script not loading, wrong module entrypoint, or missing
      data-wp-interactive
      .
  • Hydration mismatch / flicker:
    • server markup differs from client expectations; simplify or align initial state.
    • derived state not defined in PHP: use
      wp_interactivity_state()
      with closures.
  • Initial content missing or wrong:
    • supports.interactivity
      not set in
      block.json
      (for blocks).
    • wp_interactivity_process_directives()
      not called (for themes/plugins).
    • state/context not initialized in PHP before render.
  • Layout shift on load:
    • derived state like
      state.hasItems
      missing on server, causing
      hidden
      attribute to be absent.
  • Performance regressions:
    • overly broad interactive roots; scope interactivity to smaller subtrees.
  • Client-side navigation issues (WordPress 6.9):
    • getServerState()
      and
      getServerContext()
      now reset between page transitions—ensure your code doesn't assume stale values persist.
    • Router regions now support
      attachTo
      for rendering overlays (modals, pop-ups) dynamically.
  • 指令存在但无响应:
    • 视图脚本未加载、模块入口错误或缺少
      data-wp-interactive
  • Hydration不匹配/闪烁:
    • 服务器端标记与客户端预期不符;简化或对齐初始状态。
    • 派生状态未在PHP中定义:使用带闭包的
      wp_interactivity_state()
  • 初始内容缺失或错误:
    • 区块的
      block.json
      中未设置
      supports.interactivity
    • 主题/插件未调用
      wp_interactivity_process_directives()
    • 渲染前未在PHP中初始化状态/上下文。
  • 加载时布局偏移:
    • 服务器端缺少
      state.hasItems
      等派生状态,导致
      hidden
      属性缺失。
  • 性能退化:
    • 交互根范围过广;将交互性限定在更小的子树中。
  • 客户端导航问题(WordPress 6.9):
    • getServerState()
      getServerContext()
      现在会在页面切换时重置——确保代码不依赖过期的持久化值。
    • 路由区域现在支持
      attachTo
      来动态渲染覆盖层(模态框、弹窗)。

Escalation

升级处理

  • If repo build constraints are unclear, ask: "Is this using
    @wordpress/scripts
    or a custom bundler (webpack/vite)?"
  • Consult:
    • references/server-side-rendering.md
    • references/directives-quickref.md
    • references/debugging.md
  • 若代码库构建限制不明确,可询问:“是否使用
    @wordpress/scripts
    或自定义打包工具(webpack/vite)?”
  • 参考:
    • references/server-side-rendering.md
    • references/directives-quickref.md
    • references/debugging.md