Wordpress免费版Astra子主题实现多头部按页面调用问题
Astra子主题多页面自定义头部解决方案
你之前的代码不生效的核心原因是Astra主题采用钩子驱动的模板渲染逻辑,头部输出的优先级高于page.php、自定义页面模板的加载时机,直接在页面模板内修改get_header()逻辑不会触发。同时你的代码额外追加了wp_head()调用,属于重复操作,get_header()本身已经内置了wp_head()的执行逻辑。
前置准备
- 确保你已在子主题根目录创建自定义头部文件,命名必须为
header-custom.php,符合WordPress头部模板命名规范
正确实现代码
将以下代码添加到子主题的functions.php文件中即可生效:
add_filter('astra_get_header', 'custom_astra_switch_header'); function custom_astra_switch_header($header_template) { // 针对ID为5196的页面加载自定义头部 if (is_page(5196)) { $custom_header_path = get_stylesheet_directory() . '/header-custom.php'; // 校验自定义头部文件存在才加载,避免报错 if (file_exists($custom_header_path)) { return $custom_header_path; } } // 如需给自定义页面模板指定头部,取消注释下方代码,替换为你自己的模板文件名 // if (is_page_template('page-template.php')) { // $tpl_header_path = get_stylesheet_directory() . '/header-yourtpl.php'; // if (file_exists($tpl_header_path)) { // return $tpl_header_path; // } // } // 其他场景返回默认头部 return $header_template; }
生效校验
修改完成后清理三类缓存即可验证效果:
- 网站缓存(如果用了缓存插件)
- Astra主题内置静态资源缓存
- 浏览器本地缓存
内容的提问来源于stack exchange,提问作者ok_succotash
相关产品推荐
相关产品推荐

