Puddinq.com sharing knowledge

Translating strings in WordPress Javascript files

Translating strings in WordPress Javascript files

To translate strings in wordpress javascript files you need 3 things:

  • Your javascript file with translatable string
  • A json file with the translations
  • a php file that loads the javascript an connects the translation

The javascript

The javascript could look like this

// custom-script.js
(function ($) {
    // Text to be translated
    var textToTranslate = wp.i18n.__('Hello, world!', 'your-text-domain');

    // Use the translated string

To translate the javascript

wp i18n make-json

Load it in php

// Enqueue your script
function enqueue_custom_script() {
    wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), '1.0', true);

    // Set translations for your script
    wp_set_script_translations('custom-script', 'your-text-domain', get_template_directory() . '/languages');
add_action('wp_enqueue_scripts', 'enqueue_custom_script');