wp_attachment_is()WP 4.2.0

Verifies an attachment is of a given type.

1 time — 0.00137 sec (very slow) | 50000 times — 11.36 sec (slow)

No Hooks.

Return

true|false. True if one of the accepted types, false otherwise.

Usage

wp_attachment_is( $type, $post );
$type(string) (required)
Attachment type. Accepts 'image', 'audio', or 'video'.
$post(int|WP_Post)
Attachment ID or object.
Default: global $post

Examples

0

#1 Check if the attached file is a picture

Let's say we got a file attached to the post and know its ID - 54. Now we need to check if it is an image:

if( wp_attachment_is( 'image', 54 ) ){
	// image
}
else {
	// not image
}

The same check is done by wp_attachment_is_image().

Changelog

Since 4.2.0 Introduced.

wp_attachment_is() code WP 6.4.3

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' );
			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;
	}
}