WordPress主题添加自定义字体报错:Undefined constant 'filemtime'
WordPress自定义字体添加错误修复方案
核心问题诊断
你碰到的Undefined constant "filemtime"致命错误,根源是PHP函数调用语法错误,同时还有多处逻辑问题:
filemtime是PHP内置函数,必须用括号包裹参数,你写成filemtime get_template_directory_uri()的格式,会让PHP误将filemtime当作常量而非函数。get_template_directory_uri()返回的是网络URL,但filemtime需要服务器本地文件路径,应该用get_template_directory()替代。- 字体注册与入队的ID不匹配:注册时用的是
font-awesome这类ID,入队却用字体文件名,导致无法正确加载资源。 - CSS定义错误:直接把
src值赋值给字体变量,没有先通过@font-face声明字体族,font-family无法识别这类值。
修复后的完整代码
1. functions.php 修正代码
// 注册并加载自定义字体 function copper_enqueue_custom_fonts() { $theme_local_path = get_template_directory(); $theme_url = get_template_directory_uri(); // 注册Font Awesome字体样式 wp_register_style( 'custom-font-awesome', $theme_url . '/fonts/font-awesome.css', array(), filemtime($theme_local_path . '/fonts/font-awesome.css') ); // 注册Naskh阿拉伯字体样式 wp_register_style( 'custom-font-naskh', $theme_url . '/fonts/naskh.css', array(), filemtime($theme_local_path . '/fonts/naskh.css') ); // 注册Roboto英文字体样式 wp_register_style( 'custom-font-roboto', $theme_url . '/fonts/roboto.css', array(), filemtime($theme_local_path . '/fonts/roboto.css') ); // 加载所有注册的字体样式 wp_enqueue_style('custom-font-awesome'); wp_enqueue_style('custom-font-naskh'); wp_enqueue_style('custom-font-roboto'); } add_action('wp_enqueue_scripts', 'copper_enqueue_custom_fonts');
2. 字体声明CSS示例(如naskh.css)
每个字体单独用CSS文件声明@font-face,放在主题的fonts目录下:
@font-face { font-family: 'Naskh'; src: url('naskh-webfont.woff') format('woff'); font-weight: normal; font-style: normal; }
3. 主题主CSS的变量与应用
:root { --arabic-font: 'Naskh', serif; --english-font: 'Roboto', sans-serif; } [dir="rtl"] .container { font-family: var(--arabic-font); } [dir="ltr"] .container { font-family: var(--english-font); }
关键修复要点
- 函数调用规范:所有PHP函数必须以
函数名(参数)格式调用,不能省略括号。 - 路径区分使用:本地文件操作(如
filemtime)用get_template_directory(),前端资源加载用get_template_directory_uri()。 - ID匹配规则:
wp_register_style的第一个参数是唯一标识ID,wp_enqueue_style必须使用相同ID才能加载对应资源。 - 字体正确声明:必须通过
@font-face先注册字体族名称,才能在font-family中引用,直接使用src值无效。
内容的提问来源于stack exchange,提问作者Mohamed
相关产品推荐
相关产品推荐

