以您的默认语言获取原始页面的标题,并将其作为 body class 添加到使用 WPML 的 WordPress 上的翻译页面

Get the title of the original page in your default language and add it as body class to the translated page on WordPress with WPML

这是我的问题:

add_filter( 'body_class', 'wpml_body_class');
function wpml_body_class( $class ) {
    global $sitepress, $post;

    if( $sitepress->get_default_language() != ICL_LANGUAGE_CODE ) {
        $original_id = icl_object_id( $post->ID, get_post_type(), true, $sitepress->get_default_language() );
        $class[] = strtolower(get_the_title( $original_id ));
    }

    return $class;
}

这段代码工作正常。本质上,我使用 $sitepress 作为全局变量来获取我的默认语言,然后我提取 ID 以将其与 get_the_title 匹配,因此,在一天结束时,我将标题添加为 class body 的名称,这样我就可以轻松地复制原始页面的样式,而无需在翻译页面上的 CSS 样式表文件中添加一行,在本例中是法语。

到目前为止一切顺利,但需要注意的是:

因为这是标题,如果我有一个像我们的团队这样的标题,我必须在样式中添加一个破折号,它会根据我的字数而改变。如果我必须改用 URL,用 WordPress 提取它的过程会更复杂,所以我想知道如果我有任何 space 是否可以添加一个正则表达式来添加破折号.或者,如果其他人都知道如何提取 URL 而不是 get_the_title,我将不胜感激。

您需要 sanitize_title_with_dashes() 来达到您的目的 :) 由 WP 提供。参考https://codex.wordpress.org/Function_Reference/sanitize_title_with_dashes