问题描述

WordPress 设置为荷兰语。当我使用 get_the_archive_title()时,我的主题在类别归档页面上正确输出 「Categorie:Category-name」 。不过,我想要看 「Sectie:Category-name」 。

我不想更改 wp-content /languages 文件夹中的荷兰语文件,因为这将由 WordPress 更新更新。

我尝试复制该翻译文件,更改”category” 翻译,并将新的 nl_NL.mo 文件放入 my-theme /语言。这没有任何影响。

如何在不改变核心翻译文件的情况下为某些字符串实现不同的翻译?

最佳解决方案

你可以使用 gettext filter

add_filter( 'gettext', 'cyb_filter_gettext', 10, 3 );
function cyb_filter_gettext( $translated, $original, $domain ) {

    // Use the text string exactly as it is in the translation file
    if ( $translated == "Categorie: %s" ) {
        $translated = "Sectie: %s";
    }

    return $translated;
}

如果您需要使用上下文过滤翻译,请使用 gettext_with_context 过滤器:

add_filter( 'gettext_with_context', 'cyb_filter_gettext_with_context', 10, 4 );
function cyb_filter_gettext_with_context( $translated, $original, $context, $domain ) {

    // Use the text string exactly as it is in the translation file
    if ( $translated == "Categorie: %s" ) {
        $translated = "Sectie: %s";
    }

    return $translated;
}

具有上下文的翻译意味着在用于翻译字符串的 gettext 函数中给出上下文。例如,这是没有上下文的:

$translated = __( 'Search', 'textdomain' );

这就是上下文:

$translated = _x( 'Search', 'form placeholder', 'textdomain' );

类似的过滤器可用于多种翻译 ([_n()][2][_nx()][2]):ngettextngettext_with_context

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。