我刚刚使用 3 种不同的字体(包括 Rubik Mono One)进行了 3 次不同的测试,一切正常。
- 要么你把它排错了队。例如:你没有使用
<link rel="preconnect" href="https://fonts.gstatic.com">。
- 或者您正在使用某种框架,例如 Bootstrap,它优先于您的字体。
了解依赖关系和顺序
Wordpress 允许您在脚本入队时指定一个依赖数组。
$deps (string[]) (可选)已注册样式表的数组处理此样式表所依赖的。默认值:数组()
您的css 排队顺序应如下所示:
框架→google字体→样式表
如果您的样式表最后入队,则您定义的样式将高于触发顺序。
正如我所提到的,我们还需要添加 <link rel="preconnect" href="https://fonts.gstatic.com"> 才能使 Google 字体真正起作用。我们可以通过使用style_loader_tag wordpress 过滤器来做到这一点,它将过滤我们排队的 Google 字体的 HTML 链接标签。
这是最终代码。请记住,如果您使用的是框架,则必须为 Google 字体标签指定依赖项。
<?php
add_action( 'wp_enqueue_scripts', 'theme_fonts' );
function theme_fonts() {
if ( ! is_admin() ) {
/**
* Register & Enqueue gfont_css.
* @link https://developer.wordpress.org/reference/functions/wp_enqueue_style/
*/
wp_enqueue_style( 'gfont_css', 'https://fonts.googleapis.com/css2?family=Rubik+Mono+One&display=swap', [], wp_get_theme()->version, 'all' );
/**
* Add mandatory Google Font rel='preconnect' <link> and required attributes to gfont_css
* Filters the HTML link tag of an enqueued style & add required attributes
* @link https://developer.wordpress.org/reference/hooks/style_loader_tag/
*/
add_filter( 'style_loader_tag', 'data_gfont_css', 10, 3 );
function data_gfont_css( $tag, $handle, $src ) {
if( $handle === 'gfont_css' ) {
$tag = str_replace(
"<link rel='stylesheet'",
"<link rel='preconnect' href='https://fonts.gstatic.com'>" . PHP_EOL . "<link rel='stylesheet'",
$tag
);
};
return $tag;
};
/**
* Register & Enqueue style_css.
* @link https://developer.wordpress.org/reference/functions/wp_enqueue_style/
*/
wp_enqueue_style( 'style_css', get_stylesheet_uri(), [ 'gfont_css' ], wp_get_theme()->version, 'all' );
};
};
?>
在括号//... [ 'gfont_css' ] 之间指定依赖关系,这相当于array( 'gfont_css' )。
最后我们可以将我们的字体应用到style.css 中的元素上,并且我们可以添加一个!important 语句来覆盖作为冗余。如果您使用多种字体,最好不要这样做。
body {
font-family: 'Rubik Mono One', sans-serif !important;
}