如何无需插件在WordPress中停用Google Fonts
无需插件移除WordPress中的Google Fonts方法
1. 通过主题functions.php禁用已注册的Google Fonts
大部分主题或插件会通过wp_enqueue_style注册Google Fonts,你可以按以下步骤取消加载:
- 先打开浏览器开发者工具(F12),切换到「网络」标签刷新页面,筛选「样式表」,找到Google Fonts的请求链接,比如
fonts.googleapis.com/css?family=Roboto,对应的句柄(handle)通常是主题定义的,比如'google-fonts'、'roboto-font'这类名称。 - 打开子主题的
functions.php文件(别直接改父主题,否则主题更新会丢失修改),添加以下代码:
function remove_google_fonts() { // 替换成你找到的Google Fonts句柄 wp_dequeue_style('google-fonts'); wp_deregister_style('google-fonts'); } add_action('wp_enqueue_scripts', 'remove_google_fonts', 999);
- 如果不确定句柄,也可以用宽泛匹配的方式,自动识别并禁用所有来自
fonts.googleapis.com的样式:
function disable_google_fonts_wide() { global $wp_styles; foreach ($wp_styles->registered as $handle => $style) { if (strpos($style->src, 'fonts.googleapis.com') !== false) { wp_dequeue_style($handle); wp_deregister_style($handle); } } } add_action('wp_enqueue_scripts', 'disable_google_fonts_wide', 999);
2. 禁用WordPress默认Emoji加载的Google字体
WordPress自带的Emoji功能会加载Google的Noto字体,不需要的话可以直接禁用:
function disable_wp_emojis() { remove_action('wp_head', 'print_emoji_detection_script', 7); remove_action('admin_print_scripts', 'print_emoji_detection_script'); remove_action('wp_print_styles', 'print_emoji_styles'); remove_action('admin_print_styles', 'print_emoji_styles'); remove_filter('the_content_feed', 'wp_staticize_emoji'); remove_filter('comment_text_rss', 'wp_staticize_emoji'); remove_filter('wp_mail', 'wp_staticize_emoji_for_email'); } add_action('init', 'disable_wp_emojis');
3. 替换Google Fonts为本地字体(针对强制加载的主题)
如果主题硬编码了Google Fonts,上述方法无效的话,可以替换成本地字体:
- 下载需要的字体文件(比如Roboto),放到子主题新建的
fonts文件夹里。 - 在子主题的
style.css中添加本地字体声明:
@font-face { font-family: 'Roboto'; src: url('fonts/Roboto-Regular.ttf') format('truetype'); font-weight: normal; font-style: normal; } @font-face { font-family: 'Roboto'; src: url('fonts/Roboto-Bold.ttf') format('truetype'); font-weight: bold; font-style: normal; }
- 最后覆盖主题中使用Google Fonts的样式:
body, h1, h2, h3 { font-family: 'Roboto', sans-serif !important; }
4. 移除主题自定义器中的Google Fonts选项
有些主题通过自定义器提供字体选择功能,可以移除对应的加载动作:
function remove_theme_google_fonts_customizer() { // 替换成主题加载字体的动作名,比如主题可能用'theme_enqueue_google_fonts' remove_action('wp_enqueue_scripts', 'theme_enqueue_google_fonts'); } add_action('init', 'remove_theme_google_fonts_customizer');
内容的提问来源于stack exchange,提问作者Maria Yousefi
相关产品推荐
相关产品推荐

