gutenbergdocs/reference-guides/filters/i18n-filters.md

109 lines
2.6 KiB
Markdown
Raw Normal View History

2025-10-21 17:33:45 +00:00
# 国际化过滤器
国际化函数(`__()`、`_x()`、`_n()` 和 `_nx()`)可为代码中的字符串提供翻译支持。若需覆盖这些函数的返回值,可通过以下可过滤钩子实现:
- `i18n.gettext`
- `i18n.gettext_with_context`
- `i18n.ngettext`
- `i18n.ngettext_with_context`
## 过滤器参数
这些过滤器的参数设置与其对应的 PHP 函数保持一致。
### i18n.gettext
```jsx
function i18nGettextCallback( translation, text, domain ) {
return translation;
}
```
### i18n.gettext_with_context
```jsx
function i18nGettextWithContextCallback( translation, text, context, domain ) {
return translation;
}
```
### i18n.ngettext
```jsx
function i18nNgettextCallback( translation, single, plural, number, domain ) {
return translation;
}
```
### i18n.ngettext_with_context
```jsx
function i18nNgettextWithContextCallback(
translation,
single,
plural,
number,
context,
domain
) {
return translation;
}
```
## 基础示例
以下是通过 `i18n.gettext` 过滤器覆盖特定翻译的简单示例:
```jsx
// 定义过滤器回调函数
function myPluginGettextFilter( translation, text, domain ) {
if ( text === 'Create Reusable block' ) {
return '保存至 MyOrg 区块库';
}
return translation;
}
// 添加过滤器
wp.hooks.addFilter(
'i18n.gettext',
'my-plugin/override-add-to-reusable-blocks-label',
myPluginGettextFilter
);
```
## 使用"文本域"专属过滤器
出于性能考虑,建议优先使用针对特定文本域的过滤器(这样回调函数仅会在相关文本域的字符串处理时执行)。
若需绑定到文本域专属过滤器,请在标准过滤器名称后追加下划线及文本域名称。例如,当过滤文本域为 "woocommerce" 的字符串时,可使用以下过滤器:
- `i18n.gettext_woocommerce`
- `i18n.gettext_with_context_woocommerce`
- `i18n.ngettext_woocommerce`
- `i18n.ngettext_with_context_woocommerce```
使用示例如下:
```jsx
// 定义过滤器回调函数
function myPluginGettextFilter( translation, text, domain ) {
if ( text === 'Youve fulfilled all your orders' ) {
return '所有包裹已整理完毕,准备出发。干得漂亮!';
}
return translation;
}
// 添加过滤器
wp.hooks.addFilter(
'i18n.gettext_woocommerce',
'my-plugin/override-fulfilled-all-orders-text',
myPluginGettextFilter
);
```
_注意_若需过滤文本域为 `undefined` 的字符串(例如 WordPress 核心字符串),需使用 "default" 来构建过滤器名称:
- `i18n.gettext_default`
- `i18n.gettext_with_context_default`
- `i18n.ngettext_default`
- `i18n.ngettext_with_context_default`