WordPress: Make your JavaScript translatable!

If you develop plugins for WordPress there will be a moment you will need to use JavaScript. As I know you are doing things right, you still want to be able to translate any string you may use there. That’s when wp_localize_script comes in handy!

It took me some time to wrap my head around it, but after you understand it, it is fairly easy to implement.

So, according to WordPress Developer Reference wp_localize_script takes 3 arguments: $handle, $object_name and $l10n – we’ll get to that next!

If you used JS scripts on your child theme or plugin before you should be familiar with using wp_enqueue_script. To add localization to your script, you must first register or enqueue the script. Then, you can use wp_localize_script using as handle the handle you assigned in wp_register_script, assing an object name (you can choose whatever you prefer here) and pass an array with the translatable strings.

<?php

function my_child_enqueue_scripts() {
    wp_register_script( 'child-theme-scripts', get_stylesheet_directory_uri() .    '/assets/js/main.js', array( 'jquery' ) );

    $params = array(
        'i18n_your_custom_message'  => __( 'A custom message here', 'my_text_domain' ),
        'i18n_your_second_message'  => __( 'A second message', 'my_text_domain' )
);

     wp_localize_script( 'child-theme-scripts', 'child_theme_scripts_params', $params );
     wp_enqueue_script( 'child-theme-scripts' );
}
add_action( 'admin_enqueue_scripts', 'my_child_enqueue_scripts' );

Now, you can use those string in your JavaScript code. How? Simple:

jQuery(document).ready(function() {
    console.log( child_theme_scripts_params.i18n_your_custom_message );
    console.log( child_theme_scripts_params.i18n_your_second_message);
});

First you access the object with the name you’ve used as second argument in wp_localize_script, in our case child_theme_scripts_params. In this object you should have all strings you’ve defined in the $params array.

Update your .pot file and your new strings should be there, ready to be translated! 😀

Pretty simple, right?

Leave a Comment

Your email address will not be published. Required fields are marked *