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 function d3j_wpcaption( $x = NULL, $attr = array(), $content = '' ) { extract( shortcode_atts( array( 'id' => '', 'align' => 'alignnone', 'width' => '', 'caption' => ''), $attr ) ); if ( intval( $width ) < 1 || empty( $caption ) ) return $content; $id = $id ? ( ' id="' . $id . '" ') : ''; $ret = '<div ' . $id . ' class="wp-caption ' . esc_attr( $align ) . '" style="width: ' . $width . 'px")'; $ret .= do_shortcode( $content ); $ret .= '<div class="wp-caption-wrapper">'; $ret .= '<p class="wp-caption-text">' . esc_html( $caption ) . '</p>'; $ret .= '</div>'; $ret .= '</div>'; 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.