script_module_data_(module_id) хук-фильтрWP 6.7.0

Filters data associated with a given Script Module.

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 );

Использование

add_filter( 'script_module_data_(module_id)', 'wp_kama_script_module_data_id_filter' );

/**
 * Function for `script_module_data_(module_id)` filter-hook.
 * 
 * @param array $data The data associated with the Script Module.
 *
 * @return array
 */
function wp_kama_script_module_data_id_filter( $data ){

	// filter...
	return $data;
}
$data(массив)
The data associated with the Script Module.

Список изменений

С версии 6.7.0 Введена.

Где вызывается хук

WP_Script_Modules::print_script_module_data()
script_module_data_(module_id)
wp-includes/class-wp-script-modules.php 889
$data = apply_filters( "script_module_data_{$module_id}", array() );

Где используется хук в WordPress

wp-includes/interactivity-api/class-wp-interactivity-api.php 385
add_filter( 'script_module_data_@wordpress/interactivity', array( $this, 'filter_script_module_interactivity_data' ) );
wp-includes/interactivity-api/class-wp-interactivity-api.php 386
add_filter( 'script_module_data_@wordpress/interactivity-router', array( $this, 'filter_script_module_interactivity_router_data' ) );