钩子文档

script_module_data_{$module_id}

💡 云策文档标注

概述

script_module_data_{$module_id} 是一个 WordPress 过滤器钩子,用于为指定的 Script Module 提供初始化或页面加载时必需的数据。它允许开发者动态传递数据,这些数据会以 JSON 格式嵌入页面,供客户端脚本使用。

关键要点

  • 钩子名称中的动态部分 $module_id 对应 Script Module ID,用于关联特定模块的数据。
  • 适用于传递模块初始化或页面加载时必需的数据,但不替代 REST API 或客户端数据获取。
  • 如果过滤器返回空数组,则不会在页面中嵌入任何数据。
  • 提供的数据会以 JSON 序列化形式嵌入在 ID 为 wp-script-module-data-{$module_id} 的 script 标签中。

代码示例

add_filter(
    'script_module_data_MyScriptModuleID',
    function ( array $data ): array {
        $data['dataForClient'] = 'ok';
        return $data;
    }
);

注意事项

  • 数据在客户端可通过 document.getElementById('wp-script-module-data-MyScriptModuleID') 和 JSON.parse 读取。
  • 此钩子从 WordPress 6.7.0 版本开始引入。

📄 原文内容

Filters data associated with a given Script Module.

Description

Script Modules may require data that is required for initialization or is essential to have immediately available on page load. These are suitable use cases for this data.

The dynamic portion of the hook name, $module_id, refers to the Script Module ID that the data is associated with.

This is best suited to pass essential data that must be available to the module for initialization or immediately on page load. It does not replace the REST API or fetching data from the client.

Example:

add_filter(
    'script_module_data_MyScriptModuleID',
    function ( array $data ): array {
        $data['dataForClient'] = 'ok';
        return $data;
    }
);

If the filter returns no data (an empty array), nothing will be embedded in the page.

The data for a given Script Module, if provided, will be JSON serialized in a script tag with an ID of the form wp-script-module-data-{$module_id}.

The data can be read on the client with a pattern like this:

Example:

const dataContainer = document.getElementById( 'wp-script-module-data-MyScriptModuleID' );
let data = {};
if ( dataContainer ) {
    try {
        data = JSON.parse( dataContainer.textContent );
    } catch {}
}
// data.dataForClient === 'ok';
initMyScriptModuleWithData( data );

Parameters

$dataarray
The data associated with the Script Module.

Source

$data = apply_filters( "script_module_data_{$module_id}", array() );

Changelog

Version Description
6.7.0 Introduced.