wp_get_attachment_image( int $attachment_id, string|int[] $size = 'thumbnail', bool $icon = false, string|array $attr = '' ): string

Gets an HTML img element representing an image attachment.

Description

While $size will accept an array, it is better to register a size with add_image_size() so that a cropped version is generated. It’s much more efficient than having to find the closest-sized image and then having the browser scale down the image.

Parameters

$attachment_idintrequired
Image attachment ID.
$sizestring|int[]optional
Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default 'thumbnail'.

Default:'thumbnail'

$iconbooloptional
Whether the image should be treated as an icon.

Default:false

$attrstring|arrayoptional
Attributes for the image markup.
  • src string
    Image attachment URL.
  • class string
    CSS class name or space-separated list of classes.
    Default attachment-$size_class size-$size_class, where $size_class is the image size being requested.
  • alt string
    Image description for the alt attribute.
  • srcset string
    The 'srcset' attribute value.
  • sizes string
    The 'sizes' attribute value.
  • loading string|false
    The 'loading' attribute value. Passing a value of false will result in the attribute being omitted for the image.
    Default determined by wp_get_loading_optimization_attributes().
  • decoding string
    The 'decoding' attribute value. Possible values are 'async' (default), 'sync', or 'auto'. Passing false or an empty string will result in the attribute being omitted.
  • fetchpriority string
    The 'fetchpriority' attribute value, whether high, low, or auto.
    Default determined by wp_get_loading_optimization_attributes().

Default:''

Return

string HTML img element or empty string on failure.

More Information

Usage

wp_get_attachment_image( $attachment_id, $size, $icon, $attr );

If the attachment is an image, the function returns an image at the specified size. For other attachments, the function returns a media icon if the $icon parameter is set to true.

To get attachment IDs dynamically in a template, you can use get_posts( array( 'post_type' => 'attachment' ) ), etc.

Source

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 );
		$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 );

		// Ensure that the `$width` doesn't overwrite an already valid user-provided width.
		if ( ! isset( $attr['width'] ) || ! is_numeric( $attr['width'] ) ) {
			$attr['width'] = $width;
		}

		// Ensure that the `$height` doesn't overwrite an already valid user-provided height.
		if ( ! isset( $attr['height'] ) || ! is_numeric( $attr['height'] ) ) {
			$attr['height'] = $height;
		}

		$loading_optimization_attr = wp_get_loading_optimization_attributes(
			'img',
			$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
		 * @since 6.8.2 The `$attr` array includes `width` and `height` attributes.
		 *
		 * @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 );

		if ( isset( $attr['width'] ) && is_numeric( $attr['width'] ) ) {
			$width = absint( $attr['width'] );
		}
		if ( isset( $attr['height'] ) && is_numeric( $attr['height'] ) ) {
			$height = absint( $attr['height'] );
		}
		unset( $attr['width'], $attr['height'] );

		$attr     = array_map( 'esc_attr', $attr );
		$hwstring = image_hwstring( $width, $height );
		$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 );
}

Hooks

apply_filters( ‘wp_get_attachment_image’, string $html, int $attachment_id, string|int[] $size, bool $icon, string[] $attr )

Filters the HTML img element representing an image attachment.

apply_filters( ‘wp_get_attachment_image_attributes’, string[] $attr, WP_Post $attachment, string|int[] $size )

Filters the list of attachment image attributes.

apply_filters( ‘wp_get_attachment_image_context’, string $context )

Filters the context in which wp_get_attachment_image() is used.

apply_filters( ‘wp_img_tag_add_auto_sizes’, boolean $enabled )

Filters whether auto-sizes for lazy loaded images is enabled.

Changelog

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

User Contributed Notes

  1. Skip to note 6 content

    wp_get_attachment_image function can accept four values as you can see:

    wp_get_attachment_image ( int $attachment_id, string|array $size = 'thumbnail', bool $icon = false, string|array $attr = '' )

    So i always use:

    <?php echo wp_get_attachment_image( get_the_ID(), array('700', '600'), "", array( "class" => "img-responsive" ) );  ?>

    Note: we can simply use get_the_ID() to pass id of active post. and here 700 is width and 600 is height of attachment image. we can also pass our class as array( “class” => “img-responsive” ).

  2. Skip to note 7 content

    default call returns like this:

    <img width="150" height="150" src="http://example.com/wp-content/uploads/2017/11/image-xyz-150x150.jpg&quot; class="attachment-thumbnail size-thumbnail" alt="" srcset="http://example.com/wp-content/uploads/2017/11/image-xyz-150x150.jpg 150w, http://example.com/wp-content/uploads/2017/11/image-xyz-50x50.jpg 50w" sizes="(max-width: 150px) 100vw, 150px" />
  3. Skip to note 8 content

    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>
  4. Skip to note 10 content

    To force an image to display the full size file, you can pass a single space ' ' as the srcset attribute. Note, you cannot pass an empty string, because the attribute value is tested with empty(), so an empty string will trigger the default srcset attribute to be built.

    wp_get_attachment_image( $attachment_id, 'full', false, [ 'srcset' => ' ' ] );

You must log in before being able to contribute a note or feedback.