Using WordPress ‘is_attachment()’ PHP function

The is_attachment() WordPress PHP function determines whether the query is for an existing attachment page.

Usage

is_attachment( $attachment );

Example:

if ( is_attachment( 'image-1' ) ) {
    // Display content specific to 'image-1' attachment
} else {
    // Display regular content
}

Parameters

  • $attachment (int|string|int|string|array) (Optional): Attachment ID, title, slug, or an array of such to check against. Default: ''.

More information

See WordPress Developer Resources: is_attachment()

Examples

Check if current page is an attachment

Check if the current page is an attachment and display a message accordingly.

if ( is_attachment() ) {
    echo 'You are viewing an attachment page.';
} else {
    echo 'This is not an attachment page.';
}

Display content specific to a given attachment

Display content specific to a given attachment based on its ID.

if ( is_attachment( 42 ) ) {
    // Display content for attachment with ID 42
} else {
    // Display other content
}

Display content based on attachment title

Display content specific to a given attachment based on its title.

if ( is_attachment( 'My Image' ) ) {
    // Display content for attachment with title 'My Image'
} else {
    // Display other content
}

Display content based on attachment slug

Display content specific to a given attachment based on its slug.

if ( is_attachment( 'my-image' ) ) {
    // Display content for attachment with slug 'my-image'
} else {
    // Display other content
}

Check if current page is one of multiple attachments

Check if the current page is one of several attachments and display a message accordingly.

$attachments = array( 42, 'My Image', 'my-image' );
if ( is_attachment( $attachments ) ) {
    echo 'You are viewing one of the specified attachment pages.';
} else {
    echo 'This is not one of the specified attachment pages.';
}