WordPress 3.4+ 引入 Custom Header 功能,讓用戶在後台「外觀 → 標題」上傳/裁剪/選擇頂部圖片。主題只需幾行代碼即可接入,本文詳解核心函數 header_image()、get_custom_header() 及 add_theme_support('custom-header') 配置全集。
| 函數 | 用途 | 返回值 |
|---|---|---|
header_image() | 直接輸出頂部圖片 URL | string / false |
get_header_image() | 獲取 URL(不輸出) | string / false |
get_custom_header() | 獲取完整頂部配置對象 | object (width, height, video, url...) |
header_textcolor() | 輸出頂部文字顏色 | string |
get_header_textcolor() | 獲取文字顏色 | string / 'blank' |
add_theme_support('custom-header', array(
'default-image' => '', // 默認圖片 URL
'random-default' => false, // 隨機默認圖
'width' => 980, // 建議寬度
'height' => 200, // 建議高度
'flex-height' => true, // 允許靈活高度
'flex-width' => true, // 允許靈活寬度
'default-text-color' => '333333', // 默認文字色
'header-text' => true, // 顯示文字區域
'uploads' => true, // 允許上傳
'video' => true, // 允許視頻 (WP 4.7+)
'wp-head-callback' => '', // 前台頭部回調
'admin-head-callback'=> '', // 後台預覽頭部回調
'admin-preview-callback' => '', // 後台預覽回調
));
<?php if ( get_header_image() ) : ?>
<img src="<?php header_image(); ?>"
width="<?php echo get_custom_header()->width; ?>"
height="<?php echo get_custom_header()->height; ?>"
alt="" />
<?php endif; ?>
<?php if ( $header = get_custom_header() ) : ?>
<div class="site-header"
style="background-image: url(<?php echo esc_url($header->url); ?>);
height: <?php echo $header->height; ?>px;
background-size: cover; background-position: center;">
<?php if ( display_header_text() ) : ?>
<h1 class="site-title"><a href="<?php echo esc_url(home_url('/')); ?>" style="color:#<?php header_textcolor(); ?>"><?php bloginfo('name'); ?></a></h1>
<p class="site-description" style="color:#<?php header_textcolor(); ?>"><?php bloginfo('description'); ?></p>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ( has_header_video() ) : ?>
<?php the_header_video_tag(); ?>
<?php elseif ( get_header_image() ) : ?>
<img src="<?php header_image(); ?>" ... />
<?php endif; ?>
<?php
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;
}
?>
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/HTTP 一致性
if (is_ssl()) $url = str_replace('https://', 'https://', $url);
else $url = str_replace('https://', 'https://', $url);
return esc_url_raw($url);
}
flex-width/flex-height = true,讓用戶自由裁剪比例default-image 作為主題預設視覺基調esc_url() 防 XSSheader_textcolor() 獲取,自動處理「隱藏文字」情況(返回 blank)幾行代碼賦予主題專業級頂部自定義能力,用戶無需碰代碼即可實現品牌視覺個性化。