# img_caption_shortcode()

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

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

## Сигнатура

```php
img_caption_shortcode( array $attr, string $content = '' ): string
```

## Описание

Позволяет плагину заменить содержимое, которое иначе было бы возвращено. Фильтр называется 'img_caption_shortcode' и передаёт пустую строку, значения параметров attr и content.
Поддерживаемые атрибуты шорткода: 'id', 'caption_id', 'align', 'width', 'caption' и 'class'.

## Параметры

- `$attr` `array` — обязательный. Атрибуты шорткода caption.
  
  id stringИдентификатор элемента-контейнера изображения и подписи, то есть или .
  
  caption_id stringИдентификатор элемента подписи, то есть или .
  
  align stringИмя класса, выравнивающего подпись. Значение по умолчанию 'alignnone'. Принимает 'alignleft', 'aligncenter', alignright', 'alignnone'.
  
  width intШирина подписи в пикселях.
  
  caption stringТекст подписи.
  
  class stringДополнительное имя класса (или имена), добавляемое к контейнеру подписи.
- `$content` `string` — необязательный, по умолчанию `''`. Содержимое шорткода.

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

`string`

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

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

```php
function img_caption_shortcode( $attr, $content = '' ) {
	// New-style shortcode with the caption inside the shortcode with the link and image tags.
	if ( ! isset( $attr['caption'] ) ) {
		if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
			$content         = $matches[1];
			$attr['caption'] = trim( $matches[2] );
		}
	} elseif ( str_contains( $attr['caption'], '<' ) ) {
		$attr['caption'] = wp_kses( $attr['caption'], 'post' );
	}

	/**
	 * Filters the default caption shortcode output.
	 *
	 * If the filtered output isn't empty, it will be used instead of generating
	 * the default caption template.
	 *
	 * @since 2.6.0
	 *
	 * @see img_caption_shortcode()
	 *
	 * @param string $output  The caption output. Default empty.
	 * @param array  $attr    Attributes of the caption shortcode.
	 * @param string $content The image element, possibly wrapped in a hyperlink.
	 */
	$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );

	if ( ! empty( $output ) ) {
		return $output;
	}

	$atts = shortcode_atts(
		array(
			'id'         => '',
			'caption_id' => '',
			'align'      => 'alignnone',
			'width'      => '',
			'caption'    => '',
			'class'      => '',
		),
		$attr,
		'caption'
	);

	$atts['width'] = (int) $atts['width'];

	if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) {
		return $content;
	}

	$id          = '';
	$caption_id  = '';
	$describedby = '';

	if ( $atts['id'] ) {
		$atts['id'] = sanitize_html_class( $atts['id'] );
		$id         = 'id="' . esc_attr( $atts['id'] ) . '" ';
	}

	if ( $atts['caption_id'] ) {
		$atts['caption_id'] = sanitize_html_class( $atts['caption_id'] );
	} elseif ( $atts['id'] ) {
		$atts['caption_id'] = 'caption-' . str_replace( '_', '-', $atts['id'] );
	}

	if ( $atts['caption_id'] ) {
		$caption_id  = 'id="' . esc_attr( $atts['caption_id'] ) . '" ';
		$describedby = 'aria-describedby="' . esc_attr( $atts['caption_id'] ) . '" ';
	}

	$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );

	$html5 = current_theme_supports( 'html5', 'caption' );
	// HTML5 captions never added the extra 10px to the image width.
	$width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );

	/**
	 * Filters the width of an image's caption.
	 *
	 * By default, the caption is 10 pixels greater than the width of the image,
	 * to prevent post content from running up against a floated image.
	 *
	 * @since 3.7.0
	 *
	 * @see img_caption_shortcode()
	 *
	 * @param int    $width    Width of the caption in pixels. To remove this inline style,
	 *                         return zero.
	 * @param array  $atts     Attributes of the caption shortcode.
	 * @param string $content  The image element, possibly wrapped in a hyperlink.
	 */
	$caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );

	$style = '';

	if ( $caption_width ) {
		$style = 'style="width: ' . (int) $caption_width . 'px" ';
	}

	if ( $html5 ) {
		$html = sprintf(
			'<figure %s%s%sclass="%s">%s%s</figure>',
			$id,
			$describedby,
			$style,
			esc_attr( $class ),
			do_shortcode( $content ),
			sprintf(
				'<figcaption %sclass="wp-caption-text">%s</figcaption>',
				$caption_id,
				$atts['caption']
			)
		);
	} else {
		$html = sprintf(
			'<div %s%sclass="%s">%s%s</div>',
			$id,
			$style,
			esc_attr( $class ),
			str_replace( '<img ', '<img ' . $describedby, do_shortcode( $content ) ),
			sprintf(
				'<p %sclass="wp-caption-text">%s</p>',
				$caption_id,
				$atts['caption']
			)
		);
	}

	return $html;
}
```

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

- 5.9.0 — The $content parameter default value changed from null to ''.
- 5.1.0 — The caption_id attribute was added.
- 3.9.0 — The class attribute was added.
- 2.6.0 — Introduced.

## Связанные

Использует: [`sanitize_html_class`](https://chugunov.pro/api-wordpress/functions/sanitize_html_class/), [`wp_kses`](https://chugunov.pro/api-wordpress/functions/wp_kses/), [`shortcode_atts`](https://chugunov.pro/api-wordpress/functions/shortcode_atts/), [`do_shortcode`](https://chugunov.pro/api-wordpress/functions/do_shortcode/), [`current_theme_supports`](https://chugunov.pro/api-wordpress/functions/current_theme_supports/), [`esc_attr`](https://chugunov.pro/api-wordpress/functions/esc_attr/), [`apply_filters`](https://chugunov.pro/api-wordpress/functions/apply_filters/).
Используется в: `WP_Widget_Media_Image::render_media`.

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