I have created Gutenberg blocks for my shortcodes, below is some code:
The code in PHP file in init hook to load script:
wp_register_script(
'my-blocks-script', $pluginurl . '/custom-blocks.js',
array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-editor' ),
filemtime( $plugindir . '/custom-blocks.js' )
);
// Script contains translations
if( function_exists('wp_set_script_translations') ) {
wp_set_script_translations( 'my-blocks-script', 'my-text-domain' );
}
// Shortcode block
register_block_type( 'custom-block/my-shortcode', array(
'editor_script' => 'my-blocks-script'
) );
JS code: file: custom-blocks.js
( function (blocks, editor, components, i18n, element ) {
// Define common variables
var el = wp.element.createElement;
var registerBlockType = wp.blocks.registerBlockType;
var InnerBlocks = wp.editor.InnerBlocks;
var BlockControls = wp.editor.BlockControls;
var Dashicon = wp.components.Dashicon;
var __ = wp.i18n.__;
// Shortcode
registerBlockType( 'custom-block/my-shortcode', {
title: __( 'Shortcode Title', 'my-text-domain' ),
description: '',
icon: Dashicon.cogs,
category: 'common',
attributes: {
display: {
type: 'boolean',
default: true
}
},
edit: function() {
return [
el( components.CheckboxControl, {
label: __( 'Display it?', 'my-text-domain' ),
checked: props.attributes.myAttr,
onChange: function( val ) {
props.setAttributes({ myAttr: val })
}
} ),
];
},
save: function(props) {
return(
el('div', { className: props.className }, '[my-shortcode display="'+props.attributes.display+'"]' )
);
}
} );
} ) (
window.wp.blocks,
window.wp.editor,
window.wp.components,
window.wp.i18n,
window.wp.element
);
Everything works fine, blocks display result too. but now I want to translate "Display it?" text with another language ( I use Loco Translate plugin ), I have checked po file the translation string is there, also translated strings in PHP file works fine.
Here, only the JS file transition does not work.
var i18n = wp.i18n
somewhere in your script or on the page? Because the translation library iswp.i18n
.el('div', { className: props.className }, '[my-shortcode display='"+props.attributes.display+"']' )
edit: function()
should beedit: function(props)
.