You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地WordPress站点@font-face自定义字体加载失败求助

解决WordPress自定义字体加载失败的问题

问题根源

从错误日志能明确看到,浏览器在两个错误路径下寻找字体文件:

  • 网站根目录http://my-xampp-IP/fonts/...(代码中使用了根路径/fonts/)
  • CSS文件所在目录的子文件夹.../css/fonts/...(相对路径未正确回溯到主题根目录)

而实际字体文件存放在主题根目录下的fonts文件夹,CSS文件则在主题的css文件夹中,路径不匹配直接导致404错误。

解决方案

1. 修正相对路径(最简单直接)

修改_typography.scss中的字体路径,把根路径/fonts/改成相对路径../fonts/(表示从CSS所在的css文件夹向上回溯一级到主题根目录,再进入fonts文件夹):

@font-face {
  font-family: "computerfontregular";
  src: url("../fonts/computer-font/computerfont-webfont.eot");
  src: url("../fonts/computer-font/computerfont-webfont.eot?#iefix")
      format("embedded-opentype"),
    url("../fonts/computer-font/computerfont-webfont.woff2") format("woff2"),
    url("../fonts/computer-font/computerfont-webfont.woff") format("woff"),
    url("../fonts/computer-font/computerfont-webfont.ttf") format("truetype"),
    url("../fonts/computer-font/computerfont-webfont.svg#computerfontregular")
      format("svg");
  font-weight: normal;
  font-style: normal;
}

重新编译Sass到styles.css后,浏览器就能从正确路径加载字体。

2. 使用WordPress主题路径函数(推荐,适配环境变化)

如果站点后续可能迁移域名或目录,用WordPress内置函数生成绝对路径更稳妥。在主题的functions.php中添加以下代码:

function enqueue_custom_fonts() {
    // 获取主题根目录的绝对URL
    $theme_url = get_template_directory_uri();
    // 定义字体的@font-face规则
    $font_styles = "
        @font-face {
            font-family: 'computerfontregular';
            src: url('{$theme_url}/fonts/computer-font/computerfont-webfont.eot');
            src: url('{$theme_url}/fonts/computer-font/computerfont-webfont.eot?#iefix') format('embedded-opentype'),
                 url('{$theme_url}/fonts/computer-font/computerfont-webfont.woff2') format('woff2'),
                 url('{$theme_url}/fonts/computer-font/computerfont-webfont.woff') format('woff'),
                 url('{$theme_url}/fonts/computer-font/computerfont-webfont.ttf') format('truetype'),
                 url('{$theme_url}/fonts/computer-font/computerfont-webfont.svg#computerfontregular') format('svg');
            font-weight: normal;
            font-style: normal;
        }
    ";
    // 将字体样式注入到主题主样式表中(替换为你的主题样式表句柄)
    wp_add_inline_style('theme-main-styles', $font_styles);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_fonts');

注意:把theme-main-styles替换成你主题中加载styles.css时使用的句柄(可在functions.php里查找wp_enqueue_style的第一个参数)。

3. 检查文件权限

确保主题下的fonts文件夹权限为755,字体文件权限为644,避免因权限问题导致无法访问(XAMPP中可通过文件管理器或命令行修改)。

内容的提问来源于stack exchange,提问作者Rambus_Jarbus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:40:14