钩子文档

img_caption_shortcode

💡 云策文档标注

概述

img_caption_shortcode 是一个 WordPress 过滤器钩子,用于修改默认的图片标题短代码输出。如果过滤后的输出非空,将替代默认的标题模板。

关键要点

  • 过滤器钩子:img_caption_shortcode,用于自定义图片标题短代码的输出。
  • 参数:$output(输出字符串,默认为空)、$attr(短代码属性数组)、$content(图像元素字符串,可能包含超链接)。
  • 应用场景:通过 add_filter 添加自定义函数来覆盖默认的标题生成逻辑。

代码示例

add_filter( 'img_caption_shortcode', 'my_img_caption_shortcode', 10, 3 );

function my_img_caption_shortcode( $output, $attr, $content ) {
	$attr = shortcode_atts( array(
		'id'      => '',
		'align'   => 'alignnone',
		'width'   => '',
		'caption' => ''
	), $attr );

	if ( 1 > (int) $attr['width'] || empty( $attr['caption'] ) ) {
		return '';
	}

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

	return ''
	. do_shortcode( $content )
	. '' . $attr['caption'] . ''
	. '';
}

📄 原文内容

Filters the default caption shortcode output.

Description

If the filtered output isn’t empty, it will be used instead of generating the default caption template.

See also

Parameters

$outputstring
The caption output. Default empty.
$attrarray
Attributes of the caption shortcode.
$contentstring
The image element, possibly wrapped in a hyperlink.

Source

$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );

Changelog

Version Description
2.6.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Example migrated from Codex:

    add_filter( 'img_caption_shortcode', 'my_img_caption_shortcode', 10, 3 );
    
    function my_img_caption_shortcode( $output, $attr, $content ) {
    	$attr = shortcode_atts( array(
    		'id'      => '',
    		'align'   => 'alignnone',
    		'width'   => '',
    		'caption' => ''
    	), $attr );
    
    	if ( 1 > (int) $attr['width'] || empty( $attr['caption'] ) ) {
    		return '';
    	}
    
    	if ( $attr['id'] ) {
    		$attr['id'] = 'id="' . esc_attr( $attr['id'] ) . '" ';
    	}
    
    	return '<div ' . $attr['id']
    	. 'class="wp-caption ' . esc_attr( $attr['align'] ) . '" '
    	. 'style="max-width: ' . ( 10 + (int) $attr['width'] ) . 'px;">'
    	. do_shortcode( $content )
    	. '<p class="wp-caption-text">' . $attr['caption'] . '</p>'
    	. '</div>';
    
    }