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

如何通过WordPress子主题functions.php用动作钩子正确入队CSS文件?

问题根因

  • 钩子执行顺序错误:wp_enqueue_scripts 动作的执行时机早于 get_header,你在 get_header 的回调中才注册 wp_enqueue_scripts 钩子,此时该钩子已经执行完毕,入队样式的逻辑永远不会触发。
  • 自定义模板缺失核心钩子:你编写的dashboard模板没有调用WordPress标准的wp_head()、wp_footer()函数,即便样式入队成功,WordPress也没有位置输出对应的样式标签。

修复方案

1. 替换functions.php中的代码

直接在wp_enqueue_scripts钩子回调内做页面判断即可,不需要嵌套get_header钩子:

add_action( 'wp_enqueue_scripts', function() {
    // 同时支持页面别名判断、自定义模板判断,容错性更高
    if ( is_page( 'dashboard' ) || is_page_template( 'dashboard.php' ) ) {
        // 用get_stylesheet_directory_uri()动态获取子主题路径,避免写死域名,追加版本号解决缓存问题
        wp_enqueue_style( 'dashboard-css', get_stylesheet_directory_uri() . '/css/dashboard.css', array(), wp_get_theme()->get('Version') );
    }
} );

2. 修复dashboard.php模板代码

必须在模板中加入WordPress核心的头、尾钩子,用于输出入队的资源:

<?php /*Template Name: User Dashboard*/?>
<head>
<?php wp_head(); // 所有头部资源会通过该钩子输出 ?>
</head>
<body>
<p>this is my dashboard</p>
<?php wp_footer(); // 所有底部资源会通过该钩子输出 ?>
</body>

如果需要继承Astra父主题的默认头部、底部样式,可以将wp_head()替换为get_header(),wp_footer()替换为get_footer(),符合子主题的开发规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:57:03