0

WPML 是用于管理多语言网站的优秀插件,因为它允许编辑与翻译内容相关的大量相关信息。然而,虽然这个插件添加了 hreflang 标签,但仍然缺乏对 hreflang="x-default" 注释的支持。

所以我想知道如何将这个 x-default 标签添加到 WPML 网站,并使其指向我想要的 URL 语言版本。

WPML 论坛中有一些代码示例,但它们适用于该插件的旧版本。它们都指向编辑 head_langs 函数,该函数当前包含以下代码:

function head_langs()
    {
        $languages = $this->get_ls_languages( array( 'skip_missing' => true ) );
        // If there are translations and is not paged content...

        //Renders head alternate links only on certain conditions
        $the_post = get_post();
        $the_id   = $the_post ? $the_post->ID : false;
        $is_valid = count( $languages ) > 1 && !is_paged() && ( ( ( is_single() || is_page() ) && $the_id && get_post_status( $the_id ) == 'publish' ) || ( is_home() || is_front_page() || is_archive() ) );

        if ( $is_valid ) {
            foreach ( $languages as $code => $lang ) {
                $alternate_hreflang = apply_filters( 'wpml_alternate_hreflang', $lang[ 'url' ], $code );
                printf( '<link rel="alternate" hreflang="%s" href="%s" />' . PHP_EOL,
                        $this->get_language_tag( $code ),
                        str_replace( '&amp;', '&', $alternate_hreflang ) );
            }
        }
    }
4

2 回答 2

0
/* ---------------------------------------------------------------------------
 * Set hreflang="x-default" according to Google content guidelines with WPML
 * Put into your functions.php - don't forget to use a child-theme ;-)
 * --------------------------------------------------------------------------- */
add_filter('wpml_alternate_hreflang', 'wps_head_hreflang_xdefault', 10, 2);
function wps_head_hreflang_xdefault($url, $lang_code) {

    if($lang_code == apply_filters('wpml_default_language', NULL )) {

        echo '<link rel="alternate" href="' . $url . '" hreflang="x-default" />';
    }

    return $url;
}
于 2017-04-14T12:02:24.597 回答
-1

我遇到了同样的问题,我不想覆盖核心 WPML 文件,也没有找到使用 WPML 过滤器的解决方案,所以我只是将 x-default hreflang 写入 WordPress Header,如下所示:

 // add x-default to hreflang
function x_default_hreflang() {
    $languages = icl_get_languages('skip_missing=1');
    foreach($languages as $l){
        if ( $l['language_code'] == 'en' ) { // set your default language
            $x_default_url = $l['url'];
            $output='<link rel="alternate" hreflang="x-default" href="' . $x_default_url . '" />'  . PHP_EOL;
            echo $output;
        } 
    }
}

add_action('wp_head','x_default_hreflang',1);

add_action 的优先级相当高,因此备用 hreflang 链接在其他链接下方输出,但据我所知,这并不是真正必要的。

于 2016-10-10T16:35:59.347 回答