Autonomía digital y tecnológica

Código e ideas para una internet distribuida

Linkoteca. wp_localize_script


You need to “tell” WP that your script has a translation, and specify which text domain (ID) should be used for this translation. This is done using the wp_set_script_translations() function.

So, the registration of your script with translation should look like this:

wp_register_script( ‘my-handle’, plugins_url( ‘/js/my-file.js’, __FILE__ ) );
wp_set_script_translations( ‘my-handle’, ‘my-domain’ );

The wp_set_script_translations() function adds a dependency on the main script for wp-i18n and includes the .json file.

The importance of wp_localize_script is when you can pass data directly from PHP to JavaScript.

Functions is very easy to handle there are only 3 parameters required :

$handle
(string) (Required) Script handle the data will be attached to.

$object_name
(string) (Required) Name for the JavaScript object. Passed directly, so it should be qualified JS variable. Example: ‘/[a-zA-Z0-9_]+/’.

$l10n
(array) (Required) The data itself. The data can be either a single or multi-dimensional array.