get_header
云策文档标注
概述
get_header 是一个 WordPress 钩子,在加载头部模板文件之前触发,允许开发者根据特定头部文件执行自定义代码。
关键要点
- 钩子名称:get_header,在 get_header() 函数调用开始时运行。
- 参数:$name(字符串或 null,指定头部文件名,null 表示默认头部)和 $args(数组,传递给头部模板的额外参数)。
- 用途:可用于条件性地添加动作,例如基于不同头部文件加载样式表。
- 注意事项:适合设置和执行代码,但避免直接输出内容,因为任何 echo 都会在页面标记显示前出现。
代码示例
function wpdocs_themeslug_header_hook( $name ) {
if ( 'new' == $name ) {
add_action( 'wp_enqueue_scripts', 'wpdocs_themeslug_header_style' );
}
}
add_action( 'get_header', 'wpdocs_themeslug_header_hook' );
function wpdocs_themeslug_header_style() {
wp_enqueue_style( 'wpdocs-header-new-style', get_template_directory_uri() . '/css/header-new.css' );
}
原文内容
Fires before the header template file is loaded.
Parameters
$namestring|null-
Name of the specific header file to use. Null for the default header.
$argsarray-
Additional arguments passed to the header template.
Source
do_action( 'get_header', $name, $args );
Skip to note 2 content
Collins Mbaka
The following example will enqueue stylesheets conditionally for different headers. This is just one example of how you may use the hook and will use a secondary template file of
header-new.phpfunction wpdocs_themeslug_header_hook( $name ) { if ( 'new' == $name ) { add_action( 'wp_enqueue_scripts', 'wpdocs_themeslug_header_style' ); } } add_action( 'get_header', 'wpdocs_themeslug_header_hook' ); function wpdocs_themeslug_header_style() { wp_enqueue_style( 'wpdocs-header-new-style', get_template_directory_uri() . '/css/header-new.css' ); }