I'm trying to localise my Gutenberg plugin and block, the PHP side is translated but zero luck on the js side.
I tried the official guide, few other blog posts, the solutions posted in this post enter link description here and this one enter link description here but nothing. Not even with the simplest block.
Maybe I'm missing something... Any idea? Thanks in advance.
WordPress version: 6.1.1 , PHP version: 8.0.28 , WP-CLI version: 2.7.1
EDITED as other answers recommendations: Still not working
My structure:
/my-block/
/build/
- index.js
- index.js.map
- index.asset.php
/src/
- index.js
/languages/
- my-block-es_ES.mo
- my-block-es_ES.po
- my-block-es_ES.pot
- my-block-es_ES-1fdf421c05c1140f6d71444ea2b27638.json
- block.json
- my-block.php
- package.json
- ...
The main PHP my-block.php:
<?php
/**
* Plugin Name: My Block
* Requires at least: 6.1
* Requires PHP: 7.0
* Version: 1
* Text Domain: my-block
*/
function create_block_my_block_block_init() {
register_block_type( __DIR__ );
// Load MO files for PHP.
load_plugin_textdomain( 'my-block', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
add_action( 'init', 'create_block_my_block_block_init' );
function script_translations(){
// Load JSON files for JS - this is necessary if using a custom languages path!!
wp_set_script_translations( 'my-block-local-edit-script', 'my-block', plugin_dir_path( __FILE__ ) . '/languages' );
}
add_action( 'wp_enqueue_script', 'script_translations' );
The block.json
{
"apiVersion": 2,
"title": "Test Gutenberg Block Title",
"name": "my-block/local",
"category": "layout",
"textdomain": "my-block",
"icon": "universal-access-alt",
"editorScript": "file:build/index.js"
}
And the src/index.js that compiles into build/index.js
/**
* WordPress dependencies
*/
import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';
// Register the block
registerBlockType('my-block/local', {
title: __('My Block Local', 'my-block'),
edit: function () {
return <p> {__('Hello world', 'my-block')} (from the editor)</p>;
},
save: function () {
return <p> {__('Hello world', 'my-block')} (from the frontend) </p>;
},
});
init
is far too early to callwp_set_script_translations
, way way too early. It must happen after the block is registered and enqueued.register_block_type
does not register and enqueue your blocks scripts, rather it adds hooks to do that in the future when the appropriate time occurswp_set_script_translations
andregister_block_type
to be called in the same function to work would require some form of Dr Who level time travel