wp_attachment_is() WordPress Function

The wp_attachment_is() function is used to check if an attachment is of a given type.

wp_attachment_is( string $type, int|WP_Post $post = null ) #

Verifies an attachment is of a given type.


Parameters

$type

(string)(Required)Attachment type. Accepts 'image', 'audio', or 'video'.

$post

(int|WP_Post)(Optional) Attachment ID or object. Default is global $post.

Default value: null


Top ↑

Return

(bool) True if one of the accepted types, false otherwise.


Top ↑

Source

File: wp-includes/post.php

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


Top ↑

Changelog

Changelog
VersionDescription
4.2.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More