WordPress 3.4 引入了強大的自定義頁頭功能,讓主題開發者能輕鬆實現頁頭圖片上傳、尺寸設定、文字顏色自定義等功能。本文深度解析 header_image()、get_custom_header() 等核心函數,並示範如何在主題中完整集成自定義頁頭。
header_image() - 獲取頁頭圖片 URL此函數自動判斷後台設置,返回用戶自定義的頁頭圖片地址(字符串)。若未設置則返回默認圖片或空值。
<img src="<?php header_image(); ?>"
width="<?php echo $header_image_width; ?>"
height="<?php echo $header_image_height; ?>"
alt="" />
get_header_image() 內部實現function get_header_image() {
$url = get_theme_mod('header_image', get_theme_support('custom-header', 'default-image'));
if ('remove-header' == $url) return false;
if (is_random_header_image()) $url = get_random_header_image();
// 自動適配 HTTPS
if (is_ssl()) $url = str_replace('https://', 'https://', $url);
else $url = str_replace('https://', 'https://', $url);
return esc_url_raw($url);
}
get_custom_header() - 獲取頁頭完整配置對象WordPress 3.4 新增,返回包含 width、height、video 等屬性的對象,便於統一管理頁頭參數。
// 兼容舊版本寫法
if (function_exists('get_custom_header')) {
$header_image_width = get_custom_header()->width;
$header_image_height = get_custom_header()->height;
} else {
$header_image_width = HEADER_IMAGE_WIDTH;
$header_image_height = HEADER_IMAGE_HEIGHT;
}
在主題的 functions.php 中使用 add_theme_support() 註冊:
add_theme_support('custom-header', [
'default-image' => get_template_directory_uri() . '/images/header.jpg',
'random-default' => false,
'width' => 980,
'height' => 200,
'flex-height' => true, // 允許靈活高度
'flex-width' => true, // 允許靈活寬度
'default-text-color' => '333333',
'header-text' => true, // 顯示頁頭文字
'uploads' => true, // 允許上傳
'wp-head-callback' => '', // 前台頁頭回調
'admin-head-callback' => '', // 後台預覽回調
'admin-preview-callback' => '', // 後台預覽渲染
]);
add_theme_support('custom-header', [
'width' => 1200,
'height' => 300,
'flex-width' => false,
'flex-height' => false,
]);
add_theme_support('custom-header', [
'width' => 1920,
'height' => 400,
'flex-width' => true,
'flex-height' => true,
'default-image' => get_template_directory_uri() . '/assets/images/banner-default.jpg',
]);
<?php if (get_header_image()) : ?>
<div class="site-header" style="background-image: url(<?php header_image(); ?>);">
<?php if (display_header_text()) : ?>
<h1 class="site-title"><a href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a></h1>
<p class="site-description"><?php bloginfo('description'); ?></p>
<?php endif; ?>
</div>
<?php endif; ?>
'random-default' => true 並準備多張默認圖片video 參數,配合 the_custom_header_markup() 輸出selective_refresh 實現無刷新預覽header_textcolor 動態調整文字顏色after_setup_theme 掛鉤中註冊支援esc_url() 輸出圖片地址防止 XSShas_header_image() 避免輸出空標籤flex-width 和 flex-height掌握這些函數與配置,即可輕鬆打造專業級的 WordPress 主題頁頭自定義體驗。