如何在wordpress中使用WPML插件自动跳转到相应语言的页面

  • 本文关键字:语言 wordpress 插件 WPML wordpress
  • 更新时间 :
  • 英文 :


我正在使用WPML建立一个多语言博客。使用按钮更改语言效果很好。有没有办法根据访问者的语言自动跳转?

为了改进Seh hong的优秀答案,这里是相同的代码添加到您的functions.php,除了您不需要手动设置$default_lang$supported_lang(它们是自动检索的):

add_action('init', 'my_icl_set_current_language');
add_action('wp_loaded', 'my_icl_set_current_language');
function my_icl_set_current_language() {
    global $sitepress;
    $default_lang = $sitepress->get_default_language(); //set the default language code
    $supported_lang = array_keys(icl_get_languages('skip_missing=0&orderby=code')); //set the allowed language codes 
    $get_lang = $default_lang;
    $langtemp = @$_COOKIE['lang'];
    if (in_array($langtemp, $supported_lang)) $get_lang = $langtemp;
    $langtemp = @$_GET['lang'];
    if (in_array($langtemp, $supported_lang)) $get_lang = $langtemp;
    if (in_array($get_lang, $supported_lang)) {
        //save cookie setting
        setcookie ('lang', $get_lang, time() + (10 * 365 * 24 * 60 * 60), '/');
        if ($sitepress->get_current_language() != $get_lang) {
            $sitepress->switch_lang($get_lang, true);
        }
    }
    define('CURRENT_LANGUAGE_CODE', $get_lang); //use this constant to check the current language code instead of ICL_LANGUAGE_CODE
}

如果您希望自定义WPML以允许记住访问者最后选择的语言偏好,您可以在WP functions.php中放置以下代码:

add_action('init', 'my_icl_set_current_language');
add_action('wp_loaded', 'my_icl_set_current_language');
function my_icl_set_current_language() {
    $default_lang = 'en'; //set the default language code
    $supported_lang = array('zh-hans', 'en'); //set the allowed language codes 
    $get_lang = $default_lang;
    $langtemp = @$_COOKIE['lang'];
    if (in_array($langtemp, $supported_lang)) $get_lang = $langtemp;
    $langtemp = @$_GET['lang'];
    if (in_array($langtemp, $supported_lang)) $get_lang = $langtemp;
    if (in_array($get_lang, $supported_lang)) {
        //save cookie setting
        setcookie ('lang', $get_lang, time() + (10 * 365 * 24 * 60 * 60), '/');
        global $sitepress;
        if ( $sitepress->get_current_language() != $get_lang ) {
                $sitepress->switch_lang($get_lang, true);
        }
    }
    define('CURRENT_LANGUAGE_CODE', $get_lang); //use this constant to check the current language code instead of ICL_LANGUAGE_CODE
}

有了这个自定义,访问者只需要访问http://www.yoursite.com/?lang=zh-hans一次,然后它会记住首选项,并且所有未来请求的页面都应该显示所选择的语言,即相应地显示简体中文,除非选择了其他语言或lang cookie已经过期。

我们使用WPML 2.4.1(多语言CMS版本),它包含了这个功能。

WPML->Languages->

屏幕上的文档是这样说的:

WPML可以根据浏览器语言自动重定向访问者。

重要的笔记:

当启用缓存插件时,不应该使用此功能。禁用cookie的访问者在语言切换时可能会遇到困难。

  • 禁用浏览器语言重定向

  • 仅当存在翻译时,根据浏览器语言重定向访问者

  • 始终根据浏览器语言重定向访问者(如果缺少翻译则重定向到主页)

记住访问者在24小时内的语言偏好。

最新更新