WP_Query::is_attachment()publicWP 3.1.0

Determines whether the query is for an existing attachment page.

Method of the class: WP_Query{}

No Hooks.

Return

true|false. Whether the query is for an existing attachment page.

Usage

global $wp_query;
$wp_query->is_attachment( $attachment );
$attachment(int|string|int[]|string[])
Attachment ID, title, slug, or array of such to check against.
Default: ''

Changelog

Since 3.1.0 Introduced.

WP_Query::is_attachment() code WP 6.5.2

public function is_attachment( $attachment = '' ) {
	if ( ! $this->is_attachment ) {
		return false;
	}

	if ( empty( $attachment ) ) {
		return true;
	}

	$attachment = array_map( 'strval', (array) $attachment );

	$post_obj = $this->get_queried_object();
	if ( ! $post_obj ) {
		return false;
	}

	if ( in_array( (string) $post_obj->ID, $attachment, true ) ) {
		return true;
	} elseif ( in_array( $post_obj->post_title, $attachment, true ) ) {
		return true;
	} elseif ( in_array( $post_obj->post_name, $attachment, true ) ) {
		return true;
	}
	return false;
}