Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gutenberg i18n : example in real life
<?php
/**
* Replace "text-domain" with your text domain, it's just the i18n load part
*/
class Gutenberg_i18n_Example {
public function hooks() {
add_action( 'enqueue_block_editor_assets', [ $this, 'scripts_register' ] );
add_action( 'enqueue_block_assets', [ $this, 'scripts_enqueue' ] );
add_action( 'init', [ $this, 'load_i18n' ] );
}
public function scripts_register() {
wp_register_script(
'block-js',
plugin_dir_url( __FILE__ ) . 'js/block.build.js',
[ 'wp-i18n' ],
filemtime( plugin_dir_path( __FILE__ ) . 'js/block.build.js' ),
true
);
wp_register_style(
'block-styles',
plugin_dir_url( __FILE__ ) . 'css/block.build.css',
[ 'wp-edit-blocks' ],
filemtime( plugin_dir_path( __FILE__ ) . 'css/block.build.css' )
);
/*
* Pass already loaded translations to our JavaScript.
*
* This happens _before_ our JavaScript runs, afterwards it's too late.
*/
wp_add_inline_script(
'block-js',
'wp.i18n.setLocaleData( ' . json_encode( $this->get_jed_locale_data( 'text-domain' ) ) . ', "text-domain" );',
'before'
);
}
public function scripts_enqueue() {
wp_enqueue_script( 'block-js' );
wp_enqueue_style( 'block-styles' );
}
protected function get_jed_locale_data( $domain ) {
$translations = get_translations_for_domain( $domain );
$locale = [
'' => [
'domain' => $domain,
'lang' => is_admin() ? get_user_locale() : get_locale(),
],
];
if ( ! empty( $translations->headers['Plural-Forms'] ) ) {
$locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
}
foreach ( $translations->entries as $msgid => $entry ) {
$locale[ $msgid ] = $entry->translations;
}
return $locale;
}
public function load_i18n() {
load_plugin_textdomain( 'text-domain', false, 'RELATIVE_PATH_FOR_LANG_DIR' );
}
}
add_action( 'plugins_loaded', 'gutenberg_i18n_load' );
function gutenberg_i18n_load() {
$gutenberg_i18n = new Gutenberg_i18n_Example();
$gutenberg_i18n->hooks();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.