具體效果如下例子:
1、添加主題支持
從 3.4 版本 開始, 主題必須在?functions.php?
文件里使用?add_theme_support()
?函數來添加自定義頂部的支持, 像這樣:
add_theme_support( 'custom-header' );
添加的默認參數列表:
$defaults = array(
'default-image' => '', //默認圖像
'random-default' => false, //是否默認隨機
'width' => 0, //寬度
'height' => 0, //高度
'flex-height' => false,
'flex-width' => false,
'default-text-color' => '', //默認文本顏色
'header-text' => true, //頂部文本開關
'uploads' => true, //是否允許上傳
'wp-head-callback' => '',
'admin-head-callback' => '',
'admin-preview-callback' => '',
);
add_theme_support( 'custom-header', $defaults );
2、范例
設置自定義頂部圖像
設置一個默認頂部圖像(寬980px和高60px):
$args = array(
'width' => 980,
'height' => 60,
'default-image' => get_template_directory_uri() . '/images/header.jpg',
);
add_theme_support( 'custom-header', $args );
上傳其他自定義頂部圖像
設置一個默認頂部圖像,并允許網站所有者上傳其他圖片:
$args = array(
'width' => 980,
'height' => 60,
'default-image' => get_template_directory_uri() . '/images/header.jpg',
'uploads' => true,
);
add_theme_support( 'custom-header', $args );
靈活定義你的主題頭部
$args = array(
'flex-width' => true,
'width' => 980,
'flex-width' => true,
'height' => 200,
'default-image' => get_template_directory_uri() . '/images/header.jpg',
);
add_theme_support( 'custom-header', $args );
3、前臺調用
<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />
PS:
主題可以在模板中通過get_header_image
判斷是否有頂部圖像,通過header_image
獲得圖像地址:
<?php if ( get_header_image() ) : ?>
?
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<img src="<?php header_image(); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" />
</a>
?
<?php endif; ?>