wp_set_script_module_translations() │ WP 7.0.0

Sets the text domain and translation directory for a registered script module.

WordPress automatically loads module translations from the default domain and the standard language-file directory. The function is needed when a module uses another text domain or its translation JSON files are in a non-standard directory.

The settings are applied to the enqueued module and its translations before JavaScript runs.

The script module must first be registered with wp_register_script_module(). For an unregistered module, the function changes nothing and returns false.

Use wp_set_script_translations() when you need to load translations for a regular script rather than a module.

No Hooks.

Returns

bool.

  • true - the translation settings were saved.
  • false - the module with the specified ID is not registered.

Usage

wp_set_script_module_translations( $id, $domain, $path ): bool;
$id(string) (required)
Registered script module ID.
$domain(string)
Text domain. It must match the domain specified in the translation functions inside JavaScript.
Default: 'default'
$path(string)

Absolute filesystem path to the directory containing translation JSON files. It must be a path to files on the server, not a URL.

When empty, WordPress uses the standard directory registered for the text domain.
Default: ''

Examples

#1 Load translations for a plugin module

Registers the module, sets its text domain and languages directory, then enqueues the module.

add_action( 'wp_enqueue_scripts', 'my_plugin_enqueue_script_module' );

function my_plugin_enqueue_script_module() {
	$module_id = 'my-plugin-frontend';

	wp_register_script_module(
		$module_id,
		plugins_url( 'build/frontend.js', __FILE__ ),
		[],
		'1.0.0'
	);

	wp_set_script_module_translations(
		$module_id,
		'my-plugin',
		plugin_dir_path( __FILE__ ) . 'languages'
	);

	wp_enqueue_script_module( $module_id );
}

Notes

See: WP_Script_Modules::set_translations()

Changelog

Since 7.0.0 Introduced.

wp_set_script_module_translations() code WP 7.1.2

function wp_set_script_module_translations( string $id, string $domain = 'default', string $path = '' ): bool {
	return wp_script_modules()->set_translations( $id, $domain, $path );
}