实施现代化的指示说明中指出,我应该补充class="no-js"
到<html>
要素
有没有办法在WordPress中使用挂钩或过滤器来实现这一点?如果可能的话,我宁愿不编辑主题文件就这样做。
实施现代化的指示说明中指出,我应该补充class="no-js"
到<html>
要素
有没有办法在WordPress中使用挂钩或过滤器来实现这一点?如果可能的话,我宁愿不编辑主题文件就这样做。
这并不是确切的答案,但你可以用钩子language_attributes
滤器此操作针对<html>
标记,它所做的只是响应lang=en
字符串,例如。您可以挂接到该字符串并用CSS类替换该字符串,如下所示:
add_filter(\'language_attributes\', \'modernizr\');
function modernizr($output) {
return $output . \' class="no-js"\';
}
只有当主题遵循WordPress Theme Development Checklist. 有时人们不遵循这一点,这打破了技术。这里的游戏有点晚了,但为了添加到@Rilwis answer,您可以将脚本添加到一个函数中,该函数检查no-js
是否添加语言属性。
虽然我没有使用Modernizr,但我确实使用了2016年的no-js检测脚本,因此包含内容基本相同。这样做,您就不必担心删除添加到wp_head
或wp_enqueue_scripts
因为当你移除过滤器时,它会自动发生。
/**
* Javascript Detection Filter
*
* remove_filter( \'language_attributes\', \'lang_atts_js_detect\' );
*/
add_filter( \'language_attributes\', \'lang_atts_js_detect\' );
function lang_atts_js_detect($output) {
return $output . \' class="no-js"\';
}
add_action( \'wp_head\', function() {
if ( has_filter( \'language_attributes\', \'lang_atts_js_detect\' ) ) {
echo "<script>(function(html){html.className = html.className.replace(/\\bno-js\\b/,\'js\')})(document.documentElement);</script>\\n";
}
}, 0);
另一种选择是使用current_theme_supports
./**
* Javascript Detection Theme Support
*
* add_theme_support( \'js-detect\' );
*/
add_action( \'init\', function() {
if ( current_theme_supports( \'js-detect\' ) && !is_admin() )
add_filter( \'language_attributes\', \'lang_atts_js_detect_class\' );
add_action( \'wp_head\', \'lang_atts_js_detect_script\', 0 );
}
function lang_atts_js_detect_class($output) {
return $output . \' class="no-js"\';
}
function lang_atts_js_detect_script() {
echo "<script>(function(html){html.className = html.className.replace(/\\bno-js\\b/,\'js\')})(document.documentElement);</script>\\n";
}
我考虑将其作为内联CSS添加到functions.php(不知道怎么做)。类似这样:function addcss() { background: $this_is_the_css_value; } 我想知道这一点。但如果有更好的选择(无需添加内联CSS)。我也想知道。