首页 文章

在wordpress中获取字符串的翻译

提问于
浏览
0

我在wordpress中有一个字符串(英文),我知道它在.po和.mo文件中有翻译,当用该语言浏览网站时,它显示在前端正确翻译 .

但是我需要在PHP脚本中进行翻译 . 不是.po / .mo文件,只是翻译后的字符串 . 注意:我不是在谈论用当前语言显示文本 .

我正在寻找一个功能,我可以提供原始字符串和语言代码,并检索翻译 . 我需要在一个脚本/请求中为所有可用语言执行此操作 - 因此一次检索所有这些数据也是可以接受的 .

我尝试过这样的测试($ languages是一个lang代码字符串数组)

foreach ($languages as $language) {
            apply_filters('locale', $language);
            $test = translate($entry_id, 'roots');
            print_r($test);
            print "<hr>";
        }

然而,这似乎只是给我英文字符串(并且en或任何变体不是$ languages语言中的一种) .

谁能指出我正确的方向?

我希望我自己可以处理.po文件,但这似乎是不必要的,因为wordpress确实能够使用模板中常用的getText函数来提取当前语言的翻译,所以我认为必须有一条较短的路径我在做 .

2 回答

  • 1

    您应该能够使用 global $locale 来"set"一个值(您实际上可以将其定义为任何值,然后将应用locale过滤器) .

    然后,您可以将要转换的字符串传递给__()函数 . 获得翻译的 Value .

    add_action( 'init', 'init_locale' );
    function init_locale(){
        // initialise the global variable on init, set it to whatever you want
        global $locale;
        $locale = "en_US";
    }
    
    // use a filter to set the locale
    add_filter( 'locale', 'set_locale' );
    function set_locale(){
        // whatever logic you want to set the country
        if ( isset( $_REQUEST['foo'] ) && $_REQUEST['foo'] == 'spanish' ){
            return 'es_ES';
        }
        // or use the global
        global $locale;
        return $locale;
    }
    
    // once everything is loaded you can get the translated text. 
    add_function( 'wp_loaded', 'translated_text' );
    function translated_text(){
        // you might have used a filter or defined the global somewhere and can use...
        $spanish = __( 'text to translate' );
    
        // or you could define the global here and then get the text.
        global $locale;
        $locale = 'fr_FR';
        $french = __( 'text to translate' );
    }
    

    如果你想要一个单一的功能,这应该工作:

    function get_translated_text( $text, $domain = 'default', $the_locale = 'en_US' ){
        // get the global
        global $locale;
        // save the current value
        $old_locale = $locale;
        // override it with our desired locale
        $locale = $the_locale;
        // get the translated text (note that the 'locale' filter will be applied)
        $translated = __( $text, $domain );
        // reset the locale
        $locale = $old_locale;
        // return the translated text
        return $translated;
    }
    
  • 0

    最后我结束了处理.mo文件以获得翻译,但它比我想象的要容易 .

    $translations = array();
    $languages = get_available_languages(ABSPATH . '../wp-content/themes/MY-THEME/lang');
    foreach ($languages as $language) {
        $mo = new MO();
        if ($mo->import_from_file(ABSPATH . '../wp-content/themes/MY-THEME/lang/' . $language . '.mo')) {
            $translations[$language] = $mo->entries;
        }
    }
    

    然后翻译在 $translations[$language][$entry_id]->translations[0] ,其中$ entry_id是英文字符串 .

相关问题