Here’s a small piece of code that will use the img_caption_shortcode filter and modify the HTML for captions. The purpose is to create a <div> that wraps the image and the caption, making that <div> the same size as the image that it contains.
[php_tag] function d3j_wpcaption( $x = NULL, $attr = array(), $content = '' ) { extract( shortcode_atts( array( 'id' =[gt] '', 'align' =[gt] 'alignnone', 'width' =[gt] '', 'caption' =[gt] ''), $attr ) ); if ( intval( $width ) [lt] 1 || empty( $caption ) ) return $content; $id = $id ? ( ' id=[qt]' . $id . '[qt] ') : ''; $ret = '[lt]div ' . $id . ' class=[qt]wp-caption ' . esc_attr( $align ) . '[qt] style=[qt]width: ' . $width . 'px[qt])'; $ret .= do_shortcode( $content ); $ret .= '[lt]div class=[qt]wp-caption-wrapper[qt][gt]'; $ret .= '[lt]p class=[qt]wp-caption-text[qt][gt]' . esc_html( $caption ) . '[lt]/p[gt]'; $ret .= '[lt]/div[gt]'; $ret .= '[lt]/div[gt]'; return $ret; } add_filter( 'img_caption_shortcode', 'd3j_wpcaption', 10, 3 );
The code works by adding a filter for ‘img_caption_shortcode’. This is called by the handler function for the caption shortcode. The results of the shortcode are wrapped by a new <div> with the caption text placed within another <div> with a class of “wp-caption-wrapper”. With these now surrounding your caption shortcode contents, the appearance of the caption and image can be styled with custom CSS.