get_custom_header()
云策文档标注
概述
get_custom_header() 函数用于获取自定义头部图像的数据,返回一个包含图像URL、缩略图URL、宽度、高度等属性的对象。该函数处理随机头部图像和默认图像逻辑,确保返回完整数据。
关键要点
- 函数返回一个对象,包含自定义头部图像的URL、缩略图URL、宽度、高度和视频支持等属性。
- 支持随机头部图像,通过 is_random_header_image() 和 _get_random_header_data() 处理。
- 当无自定义数据时,会检查主题是否支持默认图像,并尝试从 $_wp_default_headers 中匹配。
- 返回对象通过 wp_parse_args() 合并默认值,确保数据完整性。
- 相比 get_header_image(),get_custom_header() 返回的对象包含 attachment_id,便于获取不同尺寸图像。
代码示例
$custom_header = get_custom_header();
if ( ! empty( $custom_header->attachment_id ) ) {
$image = wp_get_attachment_image_url( $custom_header->attachment_id, 'image-size' );
}
原文内容
Gets the header image data.
Source
function get_custom_header() {
global $_wp_default_headers;
if ( is_random_header_image() ) {
$data = _get_random_header_data();
} else {
$data = get_theme_mod( 'header_image_data' );
if ( ! $data && current_theme_supports( 'custom-header', 'default-image' ) ) {
$directory_args = array( get_template_directory_uri(), get_stylesheet_directory_uri() );
$data = array();
$data['url'] = vsprintf( get_theme_support( 'custom-header', 'default-image' ), $directory_args );
$data['thumbnail_url'] = $data['url'];
if ( ! empty( $_wp_default_headers ) ) {
foreach ( (array) $_wp_default_headers as $default_header ) {
$url = vsprintf( $default_header['url'], $directory_args );
if ( $data['url'] === $url ) {
$data = $default_header;
$data['url'] = $url;
$data['thumbnail_url'] = vsprintf( $data['thumbnail_url'], $directory_args );
break;
}
}
}
}
}
$default = array(
'url' => '',
'thumbnail_url' => '',
'width' => get_theme_support( 'custom-header', 'width' ),
'height' => get_theme_support( 'custom-header', 'height' ),
'video' => get_theme_support( 'custom-header', 'video' ),
);
return (object) wp_parse_args( $data, $default );
}
Changelog
| Version | Description |
|---|---|
| 3.4.0 | Introduced. |
Skip to note 2 content
toby
If you want to get the custom header with a different image size use the function get_custom_header() instead of get_header_image() as the returned object has an
attachment_idvalue.$custom_header = get_custom_header(); if ( ! empty( $custom_header->attachment_id ) ) { $image = wp_get_attachment_image_url( $custom_header->attachment_id, 'image-size' ); }