函数文档

get_header()

💡 云策文档标注

概述

get_header() 函数用于加载主题的头部模板文件,支持通过参数指定特定名称的头部文件,并允许传递额外参数到模板中。

关键要点

  • 函数加载 header.php 模板,若指定 $name 参数,则优先加载 header-{$name}.php 文件。
  • 参数 $name 为字符串或 null,默认 null;$args 为数组,用于向模板传递额外数据,默认空数组。
  • 成功时返回 void,若模板不存在则返回 false。
  • 触发 get_header action hook,允许在加载前执行自定义代码。
  • 若无 header.php,则回退到默认主题的 wp-includes/theme-compat/header.php。

代码示例

// 加载默认头部
get_header();

// 加载名为 'special' 的头部文件
get_header('special');

// 传递数组参数到头部模板
get_header(null, array('author' => 'Ruhul Amin', 'age' => 23));

注意事项

  • 确保主题目录中存在相应的模板文件,如 header.php 或 header-{$name}.php。
  • 使用 $args 参数时,需在 header.php 中通过全局变量或 extract 函数访问传递的数据。
  • 函数自 WordPress 1.5.0 引入,$args 参数在 5.5.0 版本中添加。

📄 原文内容

Loads header template.

Description

Includes the header template for a theme or if a name is specified then a specialized header will be included.

For the parameter, if the file is called “header-special.php” then specify “special”.

Parameters

$namestring|nulloptional
The name of the specialized header.

Default:null

$argsarrayoptional
Additional arguments passed to the header template.

Default:array()

Return

void|false Void on success, false if the template does not exist.

More Information

If the theme contains no header.php file then the header from the default theme wp-includes/theme-compat/header.php will be included.

Source

function get_header( $name = null, $args = array() ) {
	/**
	 * Fires before the header template file is loaded.
	 *
	 * @since 2.1.0
	 * @since 2.8.0 The `$name` parameter was added.
	 * @since 5.5.0 The `$args` parameter was added.
	 *
	 * @param string|null $name Name of the specific header file to use. Null for the default header.
	 * @param array       $args Additional arguments passed to the header template.
	 */
	do_action( 'get_header', $name, $args );

	$templates = array();
	$name      = (string) $name;
	if ( '' !== $name ) {
		$templates[] = "header-{$name}.php";
	}

	$templates[] = 'header.php';

	if ( ! locate_template( $templates, true, true, $args ) ) {
		return false;
	}
}

Hooks

do_action( ‘get_header’, string|null $name, array $args )

Fires before the header template file is loaded.

Changelog

Version Description
5.5.0 The $args parameter was added.
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 9 content

    Pass array as second parameter in get_header()

     wp_nav_menu( array(
    	'menu' => 'wpdocs_primary_menu',
    	'menu_class' => 'wpdocs_header_menu',
    	'menu_id' => 'wpdocs_nav_menu',
    ) ) ) );
    ?>

    Put a code on header.php

    Output:
    Show menu item that setup in the WordPress dashboard

    Note:
    In the above code class wpdocs_header_menu assign to the menu and also id wpdocs_nav_menu assign to the menu. So you can style the menu according to the requirements.