get_header_image()
云策文档标注
概述
get_header_image() 函数用于检索自定义标题图像,返回处理后的 URL 字符串或 false。它支持随机图像选择和过滤器应用,确保 URL 的安全性和格式正确。
关键要点
- 函数返回字符串(标题图像 URL)或 false(如果未设置或设置为 'remove-header')。
- 通过 get_theme_mod() 获取主题修改值,支持默认图像和随机图像功能。
- 应用 get_header_image 过滤器,允许开发者修改返回的 URL。
- 使用 sanitize_url() 和 set_url_scheme() 对 URL 进行清理和格式化。
- 相关函数包括 get_header_image_tag()、has_header_image() 和 header_image(),用于更高级的标题图像处理。
代码示例
<img src="<?php echo get_header_image(); ?>" alt="" />注意事项
- 在 WordPress 4.4 及以上版本,建议优先使用 get_header_image_tag() 函数,它返回包含 srcset 属性的 <img> 标签,支持响应式图像。
- 可以使用 the_custom_header_markup() 替代手动构建图像标记,以简化代码。
原文内容
Retrieves header image for custom header.
Source
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();
}
/**
* Filters the header image URL.
*
* @since 6.1.0
*
* @param string $url Header image URL.
*/
$url = apply_filters( 'get_header_image', $url );
if ( ! is_string( $url ) ) {
return false;
}
$url = trim( $url );
return sanitize_url( set_url_scheme( $url ) );
}
Hooks
- apply_filters( ‘get_header_image’, string $url )
-
Filters the header image URL.
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |
Skip to note 5 content
Jesse Dyck
Before using this, check out get_header_image_tag() first. That’s a new function in 4.4 that’ll return an tag including the srcset attributes for responsive images.
https://developer.wordpress.org/reference/functions/get_header_image_tag/
Skip to note 6 content
Muhammad Ijaz Anjum
can be use in place of
[html]
<img alt="" src="<?php header_image() ; ?>” width=”get_custom_header() ->width; ?>” height=”get_custom_header() ->height; ?>”>[/html]
Skip to note 7 content
Anthony Hortin
Related:
header_image
has_header_image
Skip to note 8 content
Codex
Example
<img src="<?php echo esc_url( get_header_image() ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'title' ) ) ); ?>" />