wp_set_script_translations( string $handle, string $domain = ‘default’, string $path =  ): bool

Sets translated strings for a script.

Description

Works only if the script has already been registered.

See also

Parameters

$handlestringrequired
Script handle the textdomain will be attached to.
$domainstringoptional
Text domain. Default 'default'.

Default:'default'

$pathstringoptional
The full file path to the directory containing translation files.

Default:''

Return

bool True if the text domain was successfully localized, false otherwise.

Source

function wp_set_script_translations( $handle, $domain = 'default', $path = '' ) {
	global $wp_scripts;

	if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
		_wp_scripts_maybe_doing_it_wrong( __FUNCTION__, $handle );
		return false;
	}

	return $wp_scripts->set_translations( $handle, $domain, $path );
}

Changelog

VersionDescription
5.1.0The $domain parameter was made optional.
5.0.0Introduced.

User Contributed Notes

  1. Skip to note 4 content

    If you have to generate your own JSON language pack files, use WP CLI to generate your JSON file for you. Just navigate to your plugin folder and run the following command.

    wp i18n make-json languages

    Then set the language folder in wp_set_script_translations

    wp_set_script_translations( 'wp-presenter-pro-js', 'wp-presenter-pro', plugin_dir_path( __FILE__ ) . 'languages' );

    Warning: If someone translates your plugin with the same locale on the WordPress Plugin Directory, the language will not show up if using the third argument.

  2. Skip to note 5 content

    Remember to check the path in the third argument. I wasted 3 days investigating what’s wrong and it turned out I gave

    plugin_basename( __DIR__ ) . '/languages/'

    instead of

    plugin_dir_path( __FILE__ ) . '/languages/'

    With plugin_dir_path() works fine.

  3. Skip to note 6 content

    wp_set_script_translations() should not be called before register or wp_enqueue_scripts or with init hook. To make wordpress able to load handled scripts this function should be called after text domain handled script load. Here is an example:

    add_action( 'wp_enqueue_scripts', array( $this, 'wpdocs_load_scripts' ) );
    
    add_action( 'wp_enqueue_scripts', array( $this, 'wpdocs_load_text_domain' ), 100 );
    
    function wpdocs_load_text_domain() {
        wp_set_script_translations( 
             'wpdocs-js',
             'wpdocs-text-domain',
             plugin_dir_path( __FILE__ ) . 'languages' 
        );
    }

You must log in before being able to contribute a note or feedback.