How to set the localization for a Gutenberg block?

Summary: Perhaps like me, you just need to rename, relocate and/or manually load your script/JSON translations files?


So I created a block using the npx @wordpress/create-block gutenpride command, then I created the translation stuff (POT, PO, MO and JSON/JED files) and my plugin structure was like so (but some files like src/* were not included):

gutenpride/
    build/
        index.asset.php
        index.css
        index.js
        style-index.css
    languages/
        gutenpride-de_DE-1b3034803df8a21550db0d04471ea571.json
        gutenpride-de_DE.mo
        gutenpride-de_DE.po
        gutenpride.pot
    block.json
    gutenpride.php
  • 1b3034803df8a21550db0d04471ea571 is the MD5 hash of relative path to the built editor script at build/index.js, i.e. in PHP, md5( 'build/index.js' ).

  • In my block metadata file (block.json), I got these lines:

    "name": "create-block/gutenpride",
    ...
    "textdomain": "gutenpride",
    "editorScript": "file:./build/index.js",
    

And after debugging, I found out that if textdomain is not empty (i.e. a text domain is specified), then WordPress will automatically run the final step here: https://developer.wordpress.org/block-editor/how-to-guides/internationalization/#how-to-use-i18n-in-javascript, and in my case, WordPress called wp_set_script_translations( 'create-block-gutenpride-editor-script', 'gutenpride' ) — see register_block_script_handle(), but the script handle is basically <block name>-editor-script ( without any slashes (/) ).

So it’s cool that the script translations are loaded automatically, but my JSON file was placed in the languages in my plugin folder, therefore I had to re-load the translations manually like so, which I called after the register_block_type( __DIR__ ):

// ** first param = script handle; second param = text domain
wp_set_script_translations( 'create-block-gutenpride-editor-script', 'gutenpride',
    plugin_dir_path( __FILE__ ) . '/languages/' ); // ** use a full absolute path

Alternatively, move/copy your JSON/JED files to the wp-content/languages/plugins folder and then you would not need to manually load the script translations. =) (so for example, you’d have wp-content/languages/plugins/gutenpride-de_DE-1b3034803df8a21550db0d04471ea571.json)

Additionally, I also removed the ./ in the editor script path, i.e. I used "editorScript": "file:build/index.js" instead, because otherwise, then WordPress would load the wrong file because the MD5 hash will be dfbff627e6c248bcb3b61d7d06da9ca9 ( i.e. md5( './build/index.js' ) ) and not 1b3034803df8a21550db0d04471ea571 (which is what wp i18n make-json and plugins such as Loco Translate would use).

Or if you don’t want to change the editorScript value, then you’d need to edit the MD5 hash in the JSON file’s name..