wordpress - 如何使古腾堡块翻译工作?
问题描述
我刚刚建立了一个古腾堡块,我想把它翻译成不同的语言。我正在用葡萄牙语使用我的 WordPress,并且我已经进行了葡萄牙语翻译。我遵循了文档https://developer.wordpress.org/block-editor/developers/internationalization/中提供的所有步骤,但它仍然不起作用。
我的插件叫做spoiler-alert
.
我在文件夹中创建了一个.pot
名为spoileralert.pot
的/spoiler-alert/languages
文件。然后,我生成了 md5 文件,甚至使用脚本处理程序创建了一个包含所有字符串的新文件。我的语言文件夹结构如下所示:
languages
- spoileralert.pot
- spoileralert-pt_BR.po
- spoileralert-pt_BR-<HASH-CODE-1>.json
- spoileralert-pt_BR-<HASH-CODE-2>.json
- spoileralert-pt_BR-<HASH-CODE-3>.json
- spoileralert-pt_BR-spoileralert.json
这是我的 PHP 文件spoiler-alert.php
:
function spoiler_alert_spoiler_alert_block_init() {
$dir = dirname( __FILE__ );
$script_asset_path = "$dir/build/index.asset.php";
if ( ! file_exists( $script_asset_path ) ) {
throw new Error(
'You need to run `npm start` or `npm run build` for the "spoiler-alert/spoiler-alert" block first.'
);
}
$index_js = 'build/index.js';
$script_asset = require( $script_asset_path );
wp_register_script(
'spoiler-alert-spoiler-alert-block-editor',
plugins_url( $index_js, __FILE__ ),
$script_asset['dependencies'],
$script_asset['version']
);
$editor_css = 'build/index.css';
wp_register_style(
'spoiler-alert-spoiler-alert-block-editor',
plugins_url( $editor_css, __FILE__ ),
array(),
filemtime( "$dir/$editor_css" )
);
$style_css = 'build/style-index.css';
wp_register_style(
'spoiler-alert-spoiler-alert-block',
plugins_url( $style_css, __FILE__ ),
array(),
filemtime( "$dir/$style_css" )
);
register_block_type( 'spoiler-alert/spoiler-alert', array(
'editor_script' => 'spoiler-alert-spoiler-alert-block-editor',
'editor_style' => 'spoiler-alert-spoiler-alert-block-editor',
'style' => 'spoiler-alert-spoiler-alert-block',
) );
wp_set_script_translations( 'spoileralert', 'spoiler-alert', plugin_dir_path( __FILE__ ) . '/languages' );
}
add_action( 'init', 'spoiler_alert_spoiler_alert_block_init' );
在我的.js
文件中,我使用以下方法导入了翻译包:import { __ } from '@wordpress/i18n';
我正在使用以下翻译:title: __( 'Spoiler Alert', 'spoiler-alert' ),
如何使翻译正确显示?
解决方案
已经有一段时间了,但它可能对您或其他人仍然有用。我只是复制和粘贴我已经在这里回答的内容。
我已经经历过这个过程好几次了,所以我 100% 确定它工作正常。仔细完成每个步骤,您应该设法解决您可能遇到的任何问题;)
翻译终于得到了适当的开发和记录:https ://developer.wordpress.org/block-editor/developers/internationalization/
基本上,您需要:
- 使用 wp-i18n 包来定义项目中哪些是可翻译的字符串。
- 编译您的代码(
wp i18n make-pot
将在您的编译代码中搜索翻译字符串,而不是在您的源代码中)。 - 使用 WP-CLI (
wp i18n make-pot
) 创建.pot
文件,就像我们一直使用的 WP 主题和插件一样。 .po
根据我们之前创建的文件生成文件.pot
并翻译其内容。- 再次使用 WP-CLI (
wp i18n make-json
) 将我们的.po
文件转换为所需的 JSON 格式。 - 使用
wp_set_script_translations
PHP 函数加载翻译文件。
推荐阅读
- java - 不应该让具有彼此实例的类形成无限循环
- python - python请求:TypeError:__init__()得到了一个意外的关键字参数“代理”
- python-3.x - 如何在 tensorflow 对象检测 API 中获取多个边界框坐标
- isabelle - 数据类型转换函数需要很长时间来证明
- c# - 在 Property Setter 中调用方法是否正确?
- electron - 停止尝试在电子生成器更新中下载块图
- jquery - 在 Excel 文件中导出分组的数据表行
- windows - 转换文件夹中的文件列表...将逗号分隔为管道分隔
- ios - 如何让大班更优雅?
- reactjs - TS + React:有条件地使用基于 props 的接口