title: "i18n 过滤器" post_status: publish comment_status: open taxonomy: category: - gutenberg-docs post_tag: - Filters - Reference Guides - Repos


i18n 过滤器

i18n 函数(__()_x()_n()_nx())为代码中的字符串提供翻译。如果需要覆盖这些函数返回的值,可以使用以下过滤器进行过滤:

过滤器参数

这些过滤器接收的参数与其 PHP 对应函数保持一致。

i18n.gettext

function i18nGettextCallback( translation, text, domain ) {
    return translation;
}

i18n.gettext_with_context

function i18nGettextWithContextCallback( translation, text, context, domain ) {
    return translation;
}

i18n.ngettext

function i18nNgettextCallback( translation, single, plural, number, domain ) {
    return translation;
}

i18n.ngettext_with_context

function i18nNgettextWithContextCallback(
    translation,
    single,
    plural,
    number,
    context,
    domain
) {
    return translation;
}

基础示例

这是一个简单示例,使用 i18n.gettext 过滤器覆盖特定翻译。

// 定义过滤器回调函数
function myPluginGettextFilter( translation, text, domain ) {
    if ( text === 'Create Reusable block' ) {
        return 'Save to MyOrg block library';
    }
    return translation;
}

// 添加过滤器
wp.hooks.addFilter(
    'i18n.gettext',
    'my-plugin/override-add-to-reusable-blocks-label',
    myPluginGettextFilter
);

使用“文本域”特定过滤器

出于性能考虑(因为回调函数仅对相关文本域中的字符串执行),通常建议使用针对操作文本域的特定过滤器。

要附加到文本域特定过滤器,请在标准过滤器名称后追加下划线和文本域。例如,如果要过滤文本域为 "woocommerce" 的字符串,可以使用以下过滤器之一:

例如:

// 定义过滤器回调函数
function myPluginGettextFilter( translation, text, domain ) {
    if ( text === 'You’ve fulfilled all your orders' ) {
        return 'All packed up and ready to go. Good job!';
    }
    return translation;
}

// 添加过滤器
wp.hooks.addFilter(
    'i18n.gettext_woocommerce',
    'my-plugin/override-fulfilled-all-orders-text',
    myPluginGettextFilter
);

注意:要应用文本域为 undefined 的过滤器(例如 WordPress 核心字符串),请使用名称 "default" 来构建过滤器名称。