wp_get_attachment_image()WP 2.5.0

Gets the <img> tag of the image of the specified attachment (file attached to the post).

If the attachment cannot be found, an empty string will be returned.

If the attachment is an image, the code corresponding to the specified size will be returned (see the $size parameter).

For attached files of types other than images (.zip, .xls, .flv), an icon corresponding to that type will be returned (automatically determined by WordPress). By default, such an icon is not displayed; to display it, the 3rd parameter ($icon) must be set to true.

Returns

String. HTML code of the image in the <img> tag.

Usage

$img = wp_get_attachment_image( $attachment_id, $size, $icon, $attr );
$attachment_id(number) (required)
ID of the attachment whose image needs to be retrieved.
$size(string/array)

Image size. Can be specified as:

  • A string thumbnail, medium, large, full or the name of an existing size
  • An array of 2 elements defining the dimensions of the displayed image: array(32,32).

Specifying dimensions via an array does not physically reduce the image; it is only visually reduced from the most suitable prepared thumbnail (uploads).

Specifying dimensions does not affect the sizes of displayed icons for files; they are always displayed in their original size (32x32).

Instead of using an array, it is often better to register a new size using add_image_size() and use it alongside the already established (thumbnail, medium, large, or full). This approach is more efficient, as there is no need to constantly search for the appropriate size that will then be reduced by the browser.

Default: "thumbnail"

$icon(boolean)
Whether to use media icons to represent the attachment. By default, for file-type attachments (not images), the icon will not be displayed; if you need to display icons for such types of attachments, set this parameter to true.
Default: false
$attr(array)

Any attributes for the <img> tag in an array. For example:

array(
	'class'  => 'foo bar',
	'title'  => 'image title',
	'alt'    => 'image alt',
	'srcset' => '',
	'sizes'  => '',
)

alt is taken by default from the attachment data:

'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) )

Examples

0

#1 Output a ready-to-use HTML image

Let's display the medium size image (<img> tag) of the attached file with ID 651:

<?php echo wp_get_attachment_image( 651, 'medium'); ?>

It outputs something like this HTML:

<img width="250" height="250" 
	 src="http://example.com/image-250x250.png" 
	 class="attachment-medium size-medium" 
	 alt="Text from Alt Text field"
/>

alt text will be filled in only if it is specified for the attachment in the special field (alt text). The alt does not include the text from the title, description or caption of the image.

0

#2 Example of a custom size

Display a picture of the specified size 20x20 pixels, for attachments of the "image" type, and the corresponding icon for other attachment types (the 3rd parameter):

<?php echo wp_get_attachment_image( $attach_id, [ 20,20 ], true); ?>

$attach_id - can be taken as get_post_thumbnail_id() or $post->ID if you use the loop of images. You can create such a loop by using function get_posts() (get_posts('post_type=attachment')).

0

#3 Specify class, alt and title attributes for the picture

$params = [ 'class' => 'some-class', 'alt' => 'alt picture', 'title' => 'title picture' ]

$tag = wp_get_attachment_image( 15108, 'medium', false, $params );

We get it:

<img width="588" height="216"
 src="/wp-content/uploads/2021/12/clipboard-image-122190.png"
 class="attachment-medium size-medium"
 alt="alt pictures"
 loading="lazy"
 title="title picture"/>
0

#4 Show all images attached to the post

To display all of the images and titles attached to a certain page and display them as a list of bullets you can use the following:

<ul>
	<?php if ( have_posts() ) : while ( have_posts() ) : the_post();

		$attachments = get_posts( array(
			'post_type'   => 'attachment',
			'numberposts' => -1,
			'post_status' => null,
			'post_parent' => $post->ID
		) );

		if ( $attachments ) {
			foreach ( $attachments as $attachment ) {
				?>
				<li><?php echo wp_get_attachment_image( $attachment->ID, 'full' ); ?>
					<p><?php echo apply_filters( 'the_title', $attachment->post_title ); ?></p>
				</li>
				<?php
			}
		}
	endwhile; endif; ?>
</ul>

Changelog

Since 2.5.0 Introduced.
Since 4.4.0 The $srcset and $sizes attributes were added.
Since 5.5.0 The $loading attribute was added.
Since 6.1.0 The $decoding attribute was added.

wp_get_attachment_image() code WP 6.8.1

function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) {
	$html  = '';
	$image = wp_get_attachment_image_src( $attachment_id, $size, $icon );

	if ( $image ) {
		list( $src, $width, $height ) = $image;

		$attachment = get_post( $attachment_id );
		$hwstring   = image_hwstring( $width, $height );
		$size_class = $size;

		if ( is_array( $size_class ) ) {
			$size_class = implode( 'x', $size_class );
		}

		$default_attr = array(
			'src'   => $src,
			'class' => "attachment-$size_class size-$size_class",
			'alt'   => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
		);

		/**
		 * Filters the context in which wp_get_attachment_image() is used.
		 *
		 * @since 6.3.0
		 *
		 * @param string $context The context. Default 'wp_get_attachment_image'.
		 */
		$context = apply_filters( 'wp_get_attachment_image_context', 'wp_get_attachment_image' );
		$attr    = wp_parse_args( $attr, $default_attr );

		$loading_attr              = $attr;
		$loading_attr['width']     = $width;
		$loading_attr['height']    = $height;
		$loading_optimization_attr = wp_get_loading_optimization_attributes(
			'img',
			$loading_attr,
			$context
		);

		// Add loading optimization attributes if not available.
		$attr = array_merge( $attr, $loading_optimization_attr );

		// Omit the `decoding` attribute if the value is invalid according to the spec.
		if ( empty( $attr['decoding'] ) || ! in_array( $attr['decoding'], array( 'async', 'sync', 'auto' ), true ) ) {
			unset( $attr['decoding'] );
		}

		/*
		 * If the default value of `lazy` for the `loading` attribute is overridden
		 * to omit the attribute for this image, ensure it is not included.
		 */
		if ( isset( $attr['loading'] ) && ! $attr['loading'] ) {
			unset( $attr['loading'] );
		}

		// If the `fetchpriority` attribute is overridden and set to false or an empty string.
		if ( isset( $attr['fetchpriority'] ) && ! $attr['fetchpriority'] ) {
			unset( $attr['fetchpriority'] );
		}

		// Generate 'srcset' and 'sizes' if not already present.
		if ( empty( $attr['srcset'] ) ) {
			$image_meta = wp_get_attachment_metadata( $attachment_id );

			if ( is_array( $image_meta ) ) {
				$size_array = array( absint( $width ), absint( $height ) );
				$srcset     = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
				$sizes      = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );

				if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
					$attr['srcset'] = $srcset;

					if ( empty( $attr['sizes'] ) ) {
						$attr['sizes'] = $sizes;
					}
				}
			}
		}

		/** This filter is documented in wp-includes/media.php */
		$add_auto_sizes = apply_filters( 'wp_img_tag_add_auto_sizes', true );

		// Adds 'auto' to the sizes attribute if applicable.
		if (
			$add_auto_sizes &&
			isset( $attr['loading'] ) &&
			'lazy' === $attr['loading'] &&
			isset( $attr['sizes'] ) &&
			! wp_sizes_attribute_includes_valid_auto( $attr['sizes'] )
		) {
			$attr['sizes'] = 'auto, ' . $attr['sizes'];
		}

		/**
		 * Filters the list of attachment image attributes.
		 *
		 * @since 2.8.0
		 *
		 * @param string[]     $attr       Array of attribute values for the image markup, keyed by attribute name.
		 *                                 See wp_get_attachment_image().
		 * @param WP_Post      $attachment Image attachment post.
		 * @param string|int[] $size       Requested image size. Can be any registered image size name, or
		 *                                 an array of width and height values in pixels (in that order).
		 */
		$attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );

		$attr = array_map( 'esc_attr', $attr );
		$html = rtrim( "<img $hwstring" );

		foreach ( $attr as $name => $value ) {
			$html .= " $name=" . '"' . $value . '"';
		}

		$html .= ' />';
	}

	/**
	 * Filters the HTML img element representing an image attachment.
	 *
	 * @since 5.6.0
	 *
	 * @param string       $html          HTML img element or empty string on failure.
	 * @param int          $attachment_id Image attachment ID.
	 * @param string|int[] $size          Requested image size. Can be any registered image size name, or
	 *                                    an array of width and height values in pixels (in that order).
	 * @param bool         $icon          Whether the image should be treated as an icon.
	 * @param string[]     $attr          Array of attribute values for the image markup, keyed by attribute name.
	 *                                    See wp_get_attachment_image().
	 */
	return apply_filters( 'wp_get_attachment_image', $html, $attachment_id, $size, $icon, $attr );
}