There are 2 main issues in your code:
-
As stated in my answer, the script handle format is
<block name with slashes replaced with hypens>-editor-script
, so because your block name ismy-block/local
, then the script handle ismy-block-local-editor-script
and notmy-block-local-edit-script
. -
The correct action name is
wp_enqueue_scripts
(note the “s”) and notwp_enqueue_script
. However,wp_enqueue_scripts
would not work because that’s for the front-end (non-admin side). For admin use like the post editing screen atwp-admin/post.php
, you can use eitheradmin_enqueue_scripts
or a hook specific to the block/Gutenberg editor likeenqueue_block_editor_assets
. -
Your JSON translation file should also be using
dfbff627e6c248bcb3b61d7d06da9ca9
which is the value ofmd5( 'build/index.js' )
(no./
). So the file name should instead bemy-block-es_ES-dfbff627e6c248bcb3b61d7d06da9ca9.json
🙂That value/hash is also what you’d get when you run this via WP-CLI:
wp i18n make-json my-block-<locale>.po ./ --no-purge
after doing acd languages
in your plugin directory.
How to fix the issues 1 and 2:
-
Change the
wp_set_script_translations()
line (it’s line 20 in your code) to:wp_set_script_translations( 'my-block-local-editor-script', // script handle 'my-block', // text domain plugin_dir_path( __FILE__ ) . 'languages' // path to your translation files );
Or you can use
generate_block_asset_handle()
to generate the script handle:$script_handle = generate_block_asset_handle( 'my-block/local', 'editorScript' ); wp_set_script_translations( $script_handle, 'my-block', plugin_dir_path( __FILE__ ) . 'languages' );
-
Change the
add_action( 'wp_enqueue_script', 'script_translations' );
(line 22 in your code) to:add_action( 'enqueue_block_editor_assets', 'script_translations' ); // These also work: //add_action( 'admin_enqueue_scripts', 'script_translations' ); //add_action( 'init', 'script_translations' );
Note about using
init
: Callingregister_block_type()
will automatically and immediately register the block editor script — seeregister_block_script_handle()
, soinit
can be used to set the script translations as long as it’s called after callingregister_block_type()
.