Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Theme i18n: Add a block to allow strings in template files to be translated #33192

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ function gutenberg_reregister_core_block_types() {
'heading',
'html',
'home-link',
'i18n',
'image',
'list',
'media-text',
Expand Down Expand Up @@ -60,6 +61,7 @@ function gutenberg_reregister_core_block_types() {
'navigation.php' => 'core/navigation',
'navigation-link.php' => 'core/navigation-link',
'home-link.php' => 'core/home-link',
'i18n.php' => 'core/i18n',
'rss.php' => 'core/rss',
'search.php' => 'core/search',
'shortcode.php' => 'core/shortcode',
Expand Down
16 changes: 16 additions & 0 deletions packages/block-library/src/i18n/block.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"apiVersion": 2,
"name": "core/i18n",
"title": "i18n",
"category": "text",
"description": "Pass strings to PHP for i18n.",
"supports": {
"html": false
},
"textdomain": "default",
"attributes": {
"text": {
"type": "string"
}
}
}
16 changes: 16 additions & 0 deletions packages/block-library/src/i18n/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* WordPress dependencies
*/

/**
* Internal dependencies
*/
import metadata from './block.json';

const { name } = metadata;
export { metadata, name };

export const settings = {
edit: () => {},
save: () => {},
};
30 changes: 30 additions & 0 deletions packages/block-library/src/i18n/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

$i18n_strings_file = get_stylesheet_directory() . '/i18n.php';
if ( file_exists ( $i18n_strings_file ) ) {
require_once $i18n_strings_file;
}

/**
* Registers the block using the metadata loaded from the `block.json` file.
*
* @see https://developer.wordpress.org/block-editor/tutorials/block-tutorial/writing-your-first-block-type/
*/
function register_block_core_i18n() {
register_block_type_from_metadata(
__DIR__ . '/i18n',
array(
'render_callback' => 'render_block_i18n',
)
);
}

function render_block_i18n( $attributes ) {
if ( defined( 'i18n' ) && ! empty ( i18n[ $attributes['text'] ] ) ) {
return i18n[ $attributes['text'] ];
};

return $attributes['text'];
}

add_action( 'init', 'register_block_core_i18n' );