問題描述

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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。