wp_attachment_is()
云策文档标注
概述
wp_attachment_is() 函数用于验证附件是否属于指定类型,如 image、audio、video 或文件扩展名。它通过检查附件的 MIME 类型或文件扩展名来返回布尔值。
关键要点
- 参数 $type 为必需,可接受 image、audio、video 或文件扩展名字符串。
- 参数 $post 可选,默认为全局 $post,可以是附件 ID 或 WP_Post 对象。
- 返回值为布尔类型,true 表示附件匹配指定类型或扩展名,否则返回 false。
- 函数内部逻辑包括获取附件对象、检查文件路径、匹配 MIME 类型和文件扩展名。
- 对于特殊 MIME 类型 'import',会使用特定扩展名数组进行验证。
代码示例
function wp_attachment_is( $type, $post = null ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$file = get_attached_file( $post->ID );
if ( ! $file ) {
return false;
}
if ( str_starts_with( $post->post_mime_type, $type . '/' ) ) {
return true;
}
$check = wp_check_filetype( $file );
if ( empty( $check['ext'] ) ) {
return false;
}
$ext = $check['ext'];
if ( 'import' !== $post->post_mime_type ) {
return $type === $ext;
}
switch ( $type ) {
case 'image':
$image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'webp', 'avif', 'heic' );
return in_array( $ext, $image_exts, true );
case 'audio':
return in_array( $ext, wp_get_audio_extensions(), true );
case 'video':
return in_array( $ext, wp_get_video_extensions(), true );
default:
return $type === $ext;
}
}注意事项
- 函数依赖于 get_post()、get_attached_file() 和 wp_check_filetype() 等辅助函数。
- 对于 image、audio、video 类型,使用预定义扩展名数组进行验证,确保兼容性。
- 在 WordPress 4.2.0 版本中引入,使用时需注意版本兼容性。
原文内容
Verifies an attachment is of a given type.
Parameters
$typestringrequired-
Attachment type. Accepts
image,audio,video, or a file extension. $postint|WP_Postoptional-
Attachment ID or object. Default is global $post.
Default:
null
Source
function wp_attachment_is( $type, $post = null ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$file = get_attached_file( $post->ID );
if ( ! $file ) {
return false;
}
if ( str_starts_with( $post->post_mime_type, $type . '/' ) ) {
return true;
}
$check = wp_check_filetype( $file );
if ( empty( $check['ext'] ) ) {
return false;
}
$ext = $check['ext'];
if ( 'import' !== $post->post_mime_type ) {
return $type === $ext;
}
switch ( $type ) {
case 'image':
$image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'webp', 'avif', 'heic' );
return in_array( $ext, $image_exts, true );
case 'audio':
return in_array( $ext, wp_get_audio_extensions(), true );
case 'video':
return in_array( $ext, wp_get_video_extensions(), true );
default:
return $type === $ext;
}
}
Changelog
| Version | Description |
|---|---|
| 4.2.0 | Introduced. |