file_is_displayable_image()
云策文档标注
概述
file_is_displayable_image() 函数用于验证文件是否适合在网页中显示,主要检查图像类型是否属于可显示类型。它返回布尔值,并通过过滤器允许自定义验证逻辑。
关键要点
- 函数接受一个必需参数 $path(文件路径),返回布尔值(true 表示适合显示,false 表示不适合)。
- 内部使用 wp_getimagesize() 获取图像信息,并检查图像类型是否在预定义的可显示类型数组中(包括 IMAGETYPE_GIF、IMAGETYPE_JPEG、IMAGETYPE_PNG、IMAGETYPE_BMP、IMAGETYPE_ICO、IMAGETYPE_WEBP、IMAGETYPE_AVIF)。
- 提供过滤器 'file_is_displayable_image',允许开发者修改验证结果,参数为 $result 和 $path。
- 该函数自 WordPress 2.5.0 版本引入,常用于附件元数据生成等场景。
代码示例
function file_is_displayable_image( $path ) {
$displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_ICO, IMAGETYPE_WEBP, IMAGETYPE_AVIF );
$info = wp_getimagesize( $path );
if ( empty( $info ) ) {
$result = false;
} elseif ( ! in_array( $info[2], $displayable_image_types, true ) ) {
$result = false;
} else {
$result = true;
}
/**
* Filters whether the current image is displayable in the browser.
*
* @since 2.5.0
*
* @param bool $result Whether the image can be displayed. Default true.
* @param string $path Path to the image.
*/
return apply_filters( 'file_is_displayable_image', $result, $path );
}
原文内容
Validates that file is suitable for displaying within a web page.
Parameters
$pathstringrequired-
File path to test.
Source
function file_is_displayable_image( $path ) {
$displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_ICO, IMAGETYPE_WEBP, IMAGETYPE_AVIF );
$info = wp_getimagesize( $path );
if ( empty( $info ) ) {
$result = false;
} elseif ( ! in_array( $info[2], $displayable_image_types, true ) ) {
$result = false;
} else {
$result = true;
}
/**
* Filters whether the current image is displayable in the browser.
*
* @since 2.5.0
*
* @param bool $result Whether the image can be displayed. Default true.
* @param string $path Path to the image.
*/
return apply_filters( 'file_is_displayable_image', $result, $path );
}
Hooks
- apply_filters( ‘file_is_displayable_image’, bool $result, string $path )
-
Filters whether the current image is displayable in the browser.
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |