WP_Script_Modules::print_script_module_translations
Prints translations for all enqueued script modules.
Outputs inline <script> tags that call wp.i18n.setLocaleData() with the translated strings for each script module. This must run before the script modules execute.
Auto-detects the text domain and translation path for each module from its source URL. Modules whose text domain or path differs from the defaults can opt into a specific domain/path via WP_Script_Modules::set_translations().
Method of the class: WP_Script_Modules{}
No Hooks.
Returns
null. Nothing (null).
Usage
$WP_Script_Modules = new WP_Script_Modules(); $WP_Script_Modules->print_script_module_translations(): void;
Changelog
| Since 7.0.0 | Introduced. |
WP_Script_Modules::print_script_module_translations() WP Script Modules::print script module translations code WP 7.0
public function print_script_module_translations(): void {
// Collect all module IDs that will be on the page (enqueued + their dependencies).
$module_ids = $this->get_sorted_dependencies( $this->queue );
$set_locale_data_js_function = <<<'JS'
( domain, translations ) => {
const localeData = translations.locale_data[ domain ] || translations.locale_data.messages;
localeData[""].domain = domain;
wp.i18n.setLocaleData( localeData, domain );
}
JS;
foreach ( $module_ids as $id ) {
$domain = $this->registered[ $id ]['textdomain'] ?? 'default';
$path = $this->registered[ $id ]['translations_path'] ?? '';
$json_translations = load_script_module_textdomain( $id, $domain, $path );
if ( ! $json_translations ) {
continue;
}
$output = sprintf(
'( %s )( %s, %s );',
$set_locale_data_js_function,
wp_json_encode( $domain, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ),
$json_translations
);
$script_id = "wp-script-module-translation-data-{$id}";
$output .= "\n//# sourceURL=" . rawurlencode( $script_id );
// Ensure wp-i18n is printed; the inline script below relies on wp.i18n.setLocaleData().
if ( ! wp_script_is( 'wp-i18n', 'done' ) ) {
wp_scripts()->do_items( array( 'wp-i18n' ) );
}
wp_print_inline_script_tag( $output, array( 'id' => $script_id ) );
}
}