函数文档

img_caption_shortcode()

💡 云策文档标注

概述

img_caption_shortcode() 函数用于构建 WordPress 中图像标题短码的输出,支持通过 'img_caption_shortcode' 过滤器自定义内容。该函数处理短码属性并生成 HTML 结构,适用于插件开发者和主题定制。

关键要点

  • 函数功能:生成图像标题短码的 HTML 输出,可被 'img_caption_shortcode' 过滤器覆盖。
  • 参数说明:$attr 数组包含 id、caption_id、align、width、caption 和 class 等属性;$content 为短码内容,默认为空字符串。
  • 返回值:返回用于显示标题的 HTML 字符串。
  • 过滤器:提供 'img_caption_shortcode' 和 'img_caption_shortcode_width' 过滤器,允许修改输出和宽度。
  • 相关函数:涉及 shortcode_atts()、do_shortcode()、esc_attr() 等核心函数。
  • 版本历史:自 WordPress 2.6.0 引入,后续版本添加了 caption_id 和 class 属性支持。

代码示例

function img_caption_shortcode( $attr, $content = '' ) {
    // 处理短码属性,例如合并默认值
    $atts = shortcode_atts(
        array(
            'id'         => '',
            'caption_id' => '',
            'align'      => 'alignnone',
            'width'      => '',
            'caption'    => '',
            'class'      => '',
        ),
        $attr,
        'caption'
    );
    // 生成 HTML 输出
    $html = sprintf(
        '<div id="%s" class="wp-caption %s" style="width: %dpx">%s<p class="wp-caption-text" id="%s">%s</p></div>',
        $id,
        $class,
        $width,
        $content,
        $caption_id,
        $caption
    );
    return $html;
}

注意事项

  • 属性处理:使用 shortcode_atts() 确保属性安全并填充默认值,避免未定义索引错误。
  • HTML 转义:输出时使用 esc_attr() 对属性进行转义,防止 XSS 攻击。
  • 过滤器应用:通过 apply_filters() 允许插件修改输出,增强扩展性。
  • 版本兼容性:注意函数在不同 WordPress 版本中的参数变化,如 $content 默认值从 null 改为 ''。

📄 原文内容

Builds the Caption shortcode output.

Description

Allows a plugin to replace the content that would otherwise be returned. The filter is ‘img_caption_shortcode’ and passes an empty string, the attr parameter and the content parameter values.

The supported attributes for the shortcode are ‘id’, ‘caption_id’, ‘align’, ‘width’, ‘caption’, and ‘class’.

Parameters

$attrarrayrequired
Attributes of the caption shortcode.
  • id string
    ID of the image and caption container element, i.e. <figure> or <div>.
  • caption_id string
    ID of the caption element, i.e. <figcaption> or <p>.
  • align string
    Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft', 'aligncenter', alignright’, 'alignnone'.
  • width int
    The width of the caption, in pixels.
  • caption string
    The caption text.
  • class string
    Additional class name(s) added to the caption container.
$contentstringoptional
Shortcode content. Default empty string.

Return

string HTML content to display the caption.

Source

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;
}

Hooks

apply_filters( ‘img_caption_shortcode’, string $output, array $attr, string $content )

Filters the default caption shortcode output.

apply_filters( ‘img_caption_shortcode_width’, int $width, array $atts, string $content )

Filters the width of an image’s caption.

Changelog

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

User Contributed Notes

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