I am struggling to load translation in JavaScript for my simple plugin. Translation works for PHP, but not in JS. What seems to be the problem, how can I debug this?
-
I have loaded text domain in my plugin method and this works ok. My text domain is
instantsearch
, locale for my language ishr
load_plugin_textdomain('instantsearch', FALSE, basename( dirname( __FILE__ ) ) . '/languages/'); // returns true var_dump(__('No results', 'instantsearch')); // This shows correct translation for my language
-
I have generated .json file with WP CLI
wp i18n make-json languages/
-
This gives me new file
/myplugin/languages/instantsearch-hr-hash.json
. My JS file isassets/instant-search.js
and somewhere I have read that I need to manually rename that hash. I just copied that file two times and renamed them to the following just to try it out, so something out of those 3 should be working 🙂instantsearch-hr-47626afcca1bc179bc9eedb6abdc01ff.json instantsearch-hr-instant-search.json instantsearch-hr-instantsearch.json
-
I have registered the script for translation
wp_register_script('instant-search', plugins_url('assets/instant-search.js', __FILE__), array('jquery', 'wp-i18n'), false, true); wp_enqueue_script('instant-search'); wp_set_script_translations('instant-search', 'instantsearch', plugins_url('languages', __FILE__));
-
In the script at the very top I have tried this, but it doesn’t give me translation like in PHP, it just shows english default string
console.log(wp.i18n.__('No results', 'instantsearch'));
-
Here is example of json
{"translation-revision-date":"2019-12-31 13:41+0100","generator":"WP-CLI\/2.4.0","source":"assets\/instant-search.js","domain":"messages","locale_data":{"messages":{"":{"domain":"messages","lang":"hr","plural-forms":"nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);"},"No results":["Nema prona\u0111enih rezultata"]}}}
-
I know I can use
wp_localize_script()
to move string from PHP to JS but from WP 5.* we should be able to do it