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

WordPress Underscores主题自定义CSS加载异常排查求助

问题分析与解决

问题根源

你代码里的核心错误是误用了get_stylesheet_uri()函数:

  • 这个函数的作用是返回当前主题(或子主题)的style.css文件的完整URL,比如https://example.com/wp-content/themes/hirsch/style.css
  • 你用它拼接/css/custom-css.css后,实际请求的路径变成了https://example.com/wp-content/themes/hirsch/style.css/css/custom-css.css,这个路径根本不存在
  • 服务器找不到文件时会返回404页面的HTML内容,所以浏览器的样式编辑器里才会显示奇怪的HTML代码,而非预期的CSS

修复方案

把加载自定义CSS的代码,替换为使用get_template_directory_uri()或get_stylesheet_directory_uri()——这两个函数返回的是主题目录的根URI,而非单个文件的URL。

修正后的完整代码:

function hirsch_scripts() {
    wp_enqueue_style( 'hirsch-style', get_stylesheet_uri(), array(), _S_VERSION );
    // 替换为正确的路径函数,并添加主题样式作为依赖,保证加载顺序
    wp_enqueue_style( 'custom-css-style', get_stylesheet_directory_uri() . '/css/custom-css.css', array('hirsch-style'), null, 'all');
    wp_style_add_data( 'hirsch-style', 'rtl', 'replace' );

    wp_enqueue_script( 'hirsch-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );

    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'hirsch_scripts' );

额外优化说明

  1. 依赖关系:给custom-css-style添加array('hirsch-style')作为依赖,确保自定义CSS在主题默认样式之后加载,这样你的自定义规则优先级更高,可能不需要!important就能生效
  2. 函数选择:
    • 如果是直接使用Underscores主题(没有子主题),get_template_directory_uri()和get_stylesheet_directory_uri()效果一致
    • 如果以后要创建子主题,get_stylesheet_directory_uri()会自动指向子主题目录,更灵活

验证步骤

  1. 清空浏览器缓存和WordPress缓存(如果有缓存插件)
  2. 刷新页面,打开浏览器开发者工具的「网络」面板,查看custom-css.css的请求状态是否为200
  3. 再打开样式编辑器,确认显示的是你写的CSS代码而非HTML

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:30:04