WordPress函数:wp_attachment_is 检查附件文章的类型

追格官方小助手/ 2022年07月19日/ WordPress/ 浏览 936

WordPress中,函数 wp_attachment_is 用来验证附件的类型。可以接受的附件类型包括:'image', 'audio', or 'video'。


函数源码:


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 ( 0 === strpos( $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' );
            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;
    }
}


判断的根据也很简单,就是根据文件后缀判断的。


如果是判断是否是图片的话,还可以使用函数 wp_attachment_is_image

发表评论

暂无评论,抢个沙发...

客服 工单