这是一个利用shortcode_atts_{shortcode}
过滤器,其中caption
是本例中的短代码。
这是通过从$out[\'id\']
然后通过get_post_meta( $attachment_id, \'img_class_field\', true )
.
使用这种方法,无需在编辑器中修改字幕短代码的输出。自定义类的添加是在后台处理的。如果用户手动将class属性添加到标题快捷码中,该方法仍然有效。
/**
* Adds class to caption shortcode output via img_class_field attachment meta.
*
* @param array $out The output array of shortcode attributes.
* @param array $pairs The supported attributes and their defaults.
* @param array $atts The user defined shortcode attributes.
* @param string $shortcode The shortcode name.
*/
add_filter( \'shortcode_atts_caption\', \'wpse_shortcode_atts_caption\', 10, 4 );
function wpse_shortcode_atts_caption( $out, $pairs, $atts, $shortcode ) {
// Get the attachment id. It should be available via $out[\'id\'], but
// it will be in the format \'attachment_xxxx\' where xxxx is the id.
// We\'ll try to get the id portion and we\'ll bail if this doesn\'t work.
$attachment_id = isset( $out[\'id\'] ) && ( $out[\'id\'] ) ? $out[\'id\'] : false;
$attachment_id = (int) preg_replace( \'/^attachment_/\', \'\', $attachment_id );
if ( ! $attachment_id ) {
return $out;
}
// Get the custom image class and add it to the existing classes
$extra_image_class = get_post_meta( $attachment_id, \'img_class_field\', true );
if ( $extra_image_class ) {
$spacer = isset( $out[\'class\'] ) && ( $out[\'class\'] ) ? \' \' : \'\';
$out[\'class\'] .= esc_attr( $spacer . $extra_image_class );
}
return $out;
}
用法
添加到附件元数据中的自定义类(我使用了2来衡量):
some-class another-class
通过媒体模式添加的未修改字幕短代码示例:
[caption id="attachment_2397" align="alignnone" width="480"]<a href="http://example.com/wp-content/uploads/2017/05/image.jpg"><img src="http://example.com/wp-content/uploads/2017/05/image.jpg" alt="" width="480" height="360" class="size-full wp-image-2397" /></a> This is the caption![/caption]
Example output 1: (
theme supports 标题为HTML5):
<figure id="attachment_2397" style="width: 480px" class="wp-caption alignnone some-class another-class">
<a href="http://example.com/">
<img src="http://example.com/wp-content/uploads/2017/05/image.jpg" alt="" width="480" height="360" class="size-full wp-image-2397" srcset="http://example.com/wp-content/uploads/2017/05/image.jpg 480w, http://example.com/wp-content/uploads/2017/05/image-300x225.jpg 300w" sizes="(max-width: 480px) 100vw, 480px">
</a>
<figcaption class="wp-caption-text">This is the caption!</figcaption>
</figure>
Example output 2: (主题不支持HTML5的字幕):
<div id="attachment_2397" style="width: 490px" class="wp-caption alignnone some-class another-class">
<a href="http://example.com/wp-content/uploads/2017/05/image.jpg">
<img src="http://example.com/wp-content/uploads/2017/05/image.jpg" alt="" width="480" height="360" class="size-full wp-image-2397" srcset="http://example.com/wp-content/uploads/2017/05/image.jpg 480w, http://example.com/wp-content/uploads/2017/05/image-300x225.jpg 300w" sizes="(max-width: 480px) 100vw, 480px">
</a>
<p class="wp-caption-text">This is the caption!</p>
</div>