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

自定义WordPress主题可加载JS但样式表无法加载问题求助

问题根因

你使用了错误的WordPress动作钩子挂载样式入队函数。WordPress中无论脚本还是样式入队,统一使用wp_enqueue_scripts动作钩子,不存在名为wp_enqueue_style的原生钩子,这就是样式未加载、但脚本正常加载的核心原因。

修正方案
  • 第一步:修改functions.php中样式入队函数的挂载钩子,把add_action( 'wp_enqueue_style', 'test_enqueue_styles');替换为add_action( 'wp_enqueue_scripts', 'test_enqueue_styles');
  • 第二步:调整样式入队顺序,优先引入被依赖的资源,避免加载顺序异常
  • 第三步:修正脚本重复句柄问题,你为两个不同脚本设置了相同的句柄test-bootstrap-js,后定义的脚本会覆盖先定义的,导致第一个脚本无法加载
修正后完整的functions.php代码
<?php
function test_enqueue_styles(){
    // 优先入队被依赖的样式
    wp_enqueue_style('test-bootstrap-css', get_template_directory_uri() . "/assets/css/bootstrap.css", array(), '5.1.2');
    wp_enqueue_style('test-icons', "https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css", array(), '1.4.1');
    wp_enqueue_style('test-style', get_template_directory_uri() . "/style.css", array('test-bootstrap-css'), wp_get_theme()->get( 'Version' ));
}
// 挂载到正确的钩子上
add_action( 'wp_enqueue_scripts', 'test_enqueue_styles');

function test_enqueue_scripts(){
    // 修改重复的句柄,避免覆盖
    wp_enqueue_script('test-custom-js', get_template_directory_uri() . "/assets/js/scripts.js", array(), wp_get_theme()->get( 'Version' ), true);
    wp_enqueue_script('test-bootstrap-js', get_template_directory_uri() . "/assets/js/bootstrap.js", array(), '5.1.2', true);
    wp_enqueue_script('test-bootstrap-bundle', "https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js", array(), '5.1.1', true);
}
add_action( 'wp_enqueue_scripts', 'test_enqueue_scripts');
?>

补充说明:代码中末尾新增的true参数表示将脚本挂载到页脚(wp_footer()位置),符合前端性能优化规范,你可根据实际需求调整。

验证步骤

修改完成后清空浏览器缓存和WordPress缓存(如果安装了缓存插件),刷新页面即可看到样式正常通过wp_head()加载。

内容的提问来源于stack exchange,提问作者N.MORR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:09:03