# wp_get_attachment_image()

URL: https://chugunov.pro/api-wordpress/functions/wp_get_attachment_image/
Проверено на WordPress 6.9, обновлено 06.08.2026.
Источник: независимый русскоязычный справочник chugunov.pro. Не является официальной документацией WordPress.

Тип: функция.
Появился в версии: 2.5.0.

## Сигнатура

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

## Описание

Хотя $size принимает массив, лучше зарегистрировать размер с помощью add_image_size(), чтобы генерировалась обрезанная версия. Это гораздо эффективнее, чем искать изображение ближайшего размера, а затем масштабировать его средствами браузера.

## Параметры

- `$attachment_id` `int` — обязательный. Идентификатор вложения-изображения.
- `$size` `string|int[]` — необязательный, по умолчанию `'thumbnail'`. Размер изображения. Принимает имя любого зарегистрированного размера изображения или массив значений ширины и высоты в пикселях (именно в таком порядке). Значение по умолчанию 'thumbnail'.
- `$icon` `bool` — необязательный, по умолчанию `false`. Следует ли рассматривать изображение как значок.
- `$attr` `string|array` — необязательный, по умолчанию `''`. Атрибуты разметки изображения.
  
  src stringURL вложения-изображения.
  
  class stringИмя CSS-класса или список классов через пробел.
  
  По умолчанию attachment-$size_class size-$size_class, где $size_class — запрашиваемый размер изображения.
  
  alt stringОписание изображения для атрибута alt.
  
  srcset stringЗначение атрибута 'srcset'.
  
  sizes stringЗначение атрибута 'sizes'.
  
  loading string|falseЗначение атрибута 'loading'. Передача значения false приведёт к тому, что атрибут будет опущен для изображения.
  
  Значение по умолчанию определяется wp_get_loading_optimization_attributes().
  
  decoding stringЗначение атрибута 'decoding'. Возможные значения: 'async' (по умолчанию), 'sync' или 'auto'. Передача false или пустой строки приведёт к тому, что атрибут будет опущен.
  
  fetchpriority stringЗначение атрибута 'fetchpriority': high, low или auto.
  
  Значение по умолчанию определяется wp_get_loading_optimization_attributes().

## Возвращаемое значение

`string`

## Исходный код

Файл: `wp-includes/media.php:1068`

```php
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 );
}
```

## История изменений

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

## Связанные

Использует: [`wp_sizes_attribute_includes_valid_auto`](https://chugunov.pro/api-wordpress/functions/wp_sizes_attribute_includes_valid_auto/), [`wp_get_loading_optimization_attributes`](https://chugunov.pro/api-wordpress/functions/wp_get_loading_optimization_attributes/), [`wp_calculate_image_srcset`](https://chugunov.pro/api-wordpress/functions/wp_calculate_image_srcset/), [`wp_calculate_image_sizes`](https://chugunov.pro/api-wordpress/functions/wp_calculate_image_sizes/), [`wp_get_attachment_image_src`](https://chugunov.pro/api-wordpress/functions/wp_get_attachment_image_src/), [`image_hwstring`](https://chugunov.pro/api-wordpress/functions/image_hwstring/), [`wp_get_attachment_metadata`](https://chugunov.pro/api-wordpress/functions/wp_get_attachment_metadata/), [`wp_parse_args`](https://chugunov.pro/api-wordpress/functions/wp_parse_args/), [`absint`](https://chugunov.pro/api-wordpress/functions/absint/), [`apply_filters`](https://chugunov.pro/api-wordpress/functions/apply_filters/), [`get_post_meta`](https://chugunov.pro/api-wordpress/functions/get_post_meta/), [`get_post`](https://chugunov.pro/api-wordpress/functions/get_post/).
Используется в: `WP_Widget_Media_Image::render_media`, [`get_custom_logo`](https://chugunov.pro/api-wordpress/functions/get_custom_logo/), `WP_Media_List_Table::column_title`, [`_wp_post_thumbnail_html`](https://chugunov.pro/api-wordpress/functions/_wp_post_thumbnail_html/), `WP_Comments_List_Table::column_response`, [`get_the_post_thumbnail`](https://chugunov.pro/api-wordpress/functions/get_the_post_thumbnail/), [`wp_get_attachment_link`](https://chugunov.pro/api-wordpress/functions/wp_get_attachment_link/), [`gallery_shortcode`](https://chugunov.pro/api-wordpress/functions/gallery_shortcode/), [`set_post_thumbnail`](https://chugunov.pro/api-wordpress/functions/set_post_thumbnail/).

Оригинал в официальной документации: https://developer.wordpress.org/reference/functions/wp_get_attachment_image/
