Products
GG网络技术分享 2025-03-18 16:13 7
前面我们介绍 WordPress 官方要求主题作者切换到本地托管字体,今天简单说说如何实现在本地托管的 Google 字体。
一直以来,w.org/themes 上的存储托管主题,一直不允许使用第三方资源,包括第三方的图片,JavaScript 脚本文件,CSS 样式文件,网络字体以及其他资源。
但是这条规则的唯一的例外就是 Google 字体,因为当时没有可靠的方法来实现本地托管的网络字体,而排版又是主题设计中的一个重要组成部分。但是由于 GDPR 和隐私方面以及之前的案例的影响,Google 字体不再被视为本指南的例外。
WordPress 官方主题团队在很早之前就在 Github 发布了一段脚本教大家如何本地托管 Google 网络字体。
假如你原来是通过下面的代码加载样式和 Google 网络字体的:
function my_theme_enqueue_assets() {
// 加载主题样式
wp_enqueue_style(
'my-theme',
get_stylesheet_directory_uri() . '/style.css',
array(),
'1.0'
);
// 加载网络字体
wp_enqueue_style(
'literata',
'https://fonts.geekzu.org/css2?family=Literata&display=swap',
array(),
'1.0'
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' );
下载 WordPress 官方主题团队提供的脚本,https://github.com/WPTT/webfont-loader,放到当前主题的 inc/webfont-loader 目录下,然后在上面函数开头,加入加载这段脚本的代码:
function my_theme_enqueue_assets() {
// 加载处理文件
require_once get_theme_file_path( 'inc/wptt-webfont-loader.php' );
// 加载主题样式
wp_enqueue_style(
'my-theme',
get_stylesheet_directory_uri() . '/style.css',
array(),
'1.0'
);
// 加载网络字体
wp_add_inline_style(
'my-theme',
wptt_get_webfont_styles( 'https://fonts.geekzu.org/css2?family=Literata&display=swap' )
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' );这样就可以在本地托管 Google 网络字体了。
WordPress 5.9 版本后对块编辑器做了深度的升级,所以导致只使用经典编辑器的情况下又出现了许多的冗余代码,头部内联样式 global-styles-inline-css 和底部 duotone svg 图标的代码对于很多主题来说其实都不大兼容。
wp自学笔记我是绝对不能够忍受页面前端出现没有仍和功能的代码。经过一番折腾,现在将成果分享一下。
将以下代码复制添加到当前 WordPress 主题的 functions.php 文件中即可
add_action(\'wp_enqueue_scripts\', \'tiezhu_remove_styles_inline\');function tiezhu_remove_styles_inline(){
wp_deregister_style( \'global-styles\' );
wp_dequeue_style( \'global-styles\' );
wp_dequeue_style( \'wp-block-library\' );
wp_dequeue_style( \'wp-block-library-theme\' );
wp_dequeue_style( \'wc-block-style\' );
}
Demand feedback