get_header() 是 WordPress 主題模板系統的基石函數,負責載入 header.php 或其子模板變體。本文詳細拆解參數、子模板命名規則、載入優先級、Hook 機制與實戰場景。
<?php get_header( $name = null ); ?>
$name (string, 可選):子模板標識。傳 'home' → 載入 header-home.phpfunction get_header( $name = null ) {
do_action( 'get_header', $name ); // 觸發 Hook
$templates = array();
if ( isset($name) ) $templates[] = "header-{$name}.php";
$templates[] = 'header.php';
// 兼容舊版主題(未來將移除)
if ('' == locate_template($templates, true))
load_template( ABSPATH . WPINC . '/theme-compat/header.php');
}
header-{$name}.phpheader.phpheader-{$name}.phpheader.phpwp-includes/theme-compat/header.php<?php get_header(); ?>
<h2>Error 404 - Not Found</h2>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
<?php
if ( is_home() ) {
get_header('home'); // header-home.php
} elseif ( is_404() ) {
get_header('404'); // header-404.php
} else {
get_header(); // header.php
}
?>
do_action('get_header', $name):在載入前觸發,可用於注入頁面級 CSS/JS、修改全局變量get_footer、get_sidebar、get_template_part 同理header.php,差異化片段拆分為 header-{context}.phpheader.php 直接輸出大量 HTML,改用 get_template_part('header','nav') 等模組化wp_head 內容,掛鉤 wp_head 而非 get_header掌握 get_header() 子模板機制,能讓主題結構清晰、易維護、極易擴展,是專業 WordPress 主題開發的入門必修課。