Using WordPress ‘get_attachment_icon_src()’ PHP function

The get_attachment_icon_src() WordPress PHP function retrieves the icon URL and path for an attachment.

Usage

get_attachment_icon_src( $id, $fullsize )

Custom Example:

Input:

get_attachment_icon_src( 123, true )

Output:

array( 'https://example.com/wp-content/uploads/2023/05/icon.png', 24, 24 )

Parameters

  • $id (int) (Optional) – The attachment post ID. Default is 0 (current post).
  • $fullsize (bool) (Optional) – Whether to return the full image or just the icon. Default is false (icon).

More information

See WordPress Developer Resources: get_attachment_icon_src

This function was introduced in WordPress version 2.1.0.

Examples

Get attachment icon source for the current post

This example retrieves the icon URL and path for the current post’s attachment.

$icon_src = get_attachment_icon_src();
echo $icon_src[0]; // Outputs the icon URL

Get attachment icon source for a specific post

This example retrieves the icon URL and path for a specific attachment by post ID.

$post_id = 123;
$icon_src = get_attachment_icon_src( $post_id );
echo $icon_src[0]; // Outputs the icon URL

Get full attachment image source

This example retrieves the full attachment image URL and path instead of the icon.

$post_id = 123;
$icon_src = get_attachment_icon_src( $post_id, true );
echo $icon_src[0]; // Outputs the full image URL

Display attachment icon in an HTML image tag

This example displays the attachment icon in an HTML image tag.

$post_id = 123;
$icon_src = get_attachment_icon_src( $post_id );
echo '<img src="' . $icon_src[0] . '" width="' . $icon_src[1] . '" height="' . $icon_src[2] . '" alt="Attachment Icon">'; // Outputs the image tag

Check if attachment icon exists

This example checks if an attachment icon exists before displaying it.

$post_id = 123;
$icon_src = get_attachment_icon_src( $post_id );

if ( $icon_src ) {
    echo '<img src="' . $icon_src[0] . '" width="' . $icon_src[1] . '" height="' . $icon_src[2] . '" alt="Attachment Icon">'; // Outputs the image tag if the icon exists
} else {
    echo 'No attachment icon found.';
}