Get an HTML img element representing an image attachment

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.


wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' )
 (int) Image attachment ID.
 (string|array) Optional. Image size. Accepts any valid image size, or an array of width and height values in pixels (in that order). Default 'thumbnail'.
Default: 'thumbnail'
 (boolean) Optional. Whether the image should be treated as an icon. Default false.
Default: false
 (string|array) Optional. Attributes for the image markup. Default empty.
Default: ''


(string) HTML img element or empty string on failure.


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;
		$hwstring = image_hwstring($width, $height);
		$size_class = $size;
		if ( is_array( $size_class ) ) {
			$size_class = join( 'x', $size_class );
		$attachment = get_post($attachment_id);
		$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 ) ) ),

		$attr = wp_parse_args( $attr, $default_attr );

		// Generate 'srcset' and 'sizes' if not already present.
39 more lines...
WP Trac GitHub

Link here