WordPress主題開發中,根據分類、頁面、文章類型加載差異化Header是常見需求。本文提供基於條件標籤的三種實現模式,涵蓋分類ID/名稱/別名、頁面標題/別名/ID三大維度,代碼可直接部署於header.php。
is_category() / is_page() 判斷 → include 對應模板<?php
if (is_category()) {
if (is_category('1')) { // 分類ID=1
include(TEMPLATEPATH . '/header-cat1.php');
} elseif (is_category('2')) { // 分類ID=2
include(TEMPLATEPATH . '/header-cat2.php');
} else {
include(TEMPLATEPATH . '/header-default.php'); // 默認
}
} else {
include(TEMPLATEPATH . '/header-default.php');
}
?>
<?php
if (is_category()) {
if (is_category('Category Name')) { // 分類名稱
include(TEMPLATEPATH . '/header-cat1.php');
} elseif (is_category('category-slug')) { // 分類別名
include(TEMPLATEPATH . '/header-cat2.php');
} else {
include(TEMPLATEPATH . '/header-default.php');
}
} else {
include(TEMPLATEPATH . '/header-default.php');
}
?>
<?php
// 頁面標題
if (is_page('About')) {
include(TEMPLATEPATH . '/header-contact.php');
// 頁面別名
} elseif (is_page('subscribe')) {
include(TEMPLATEPATH . '/header-subscribe.php');
// 頁面ID
} elseif (is_page('6')) {
include(TEMPLATEPATH . '/header-contact.php');
} else {
include(TEMPLATEPATH . '/header-default.php');
}
?>
header-default.php作基礎,差異部分抽離為header-{type}.php,避免代碼重複;get_header($name) API:WP原生函數自動查找header-{$name}.php,更規範:
if (is_category('news')) get_header('news');
else get_header();
is_singular('post')、is_post_type_archive('product')、is_author()等擴展更多場景;functions.php中使用條件標籤無效(掛鉤太早),必須在模板文件中;TEMPLATEPATH常量已棄用,推薦get_template_directory();