The current[foot]version 3.2.1[/foot] implementation of image captions in WordPress has a very odd characteristic: it adds
10px
to the width of the image/caption containing
div
. I have always found the need to compensate for this inline styling when building themes, and I have never found the explanation for adding an extra 10 pixels.[foot]If you know, please
enlighten me.[/foot] As a bonus, this is a perfect place to use HTML5's
figure
/
figcaption
structure.
The code presented here is meant to solve these problems by:
- Removing the extra 10pixels to open up image/captions to easier external CSS control,[foot]For responsive designs, I remove it altogether and use percentage-based widths based on the appropriate layout size. Perhaps another post would be appropriate on that.[/foot] and
- replacing the
div
based structure with semantic HTML5 figure
/figcaption
structure.[foot]This structure is so wonderfully semantic, and is frequently appropriate.[/foot]
We're going to filter the caption output. Add the following code to your
functions.php
file:
add_filter('img_caption_shortcode', 'orangegnome_img_caption_shortcode_filter',10,3);
/**
* Removes the extra 10px of width from wp-caption and changes to HTML5 figure/figcaption
*
**/
function orangegnome_img_caption_shortcode_filter($val, $attr, $content = null) {
extract(shortcode_atts(array(
'id' => '',
'align' => '',
'width' => '',
'caption' => ''
), $attr));
if ( 1 > (int) $width || empty($caption) )
return $val;
return '<figure id="' . $id . '" class="wp-caption ' . esc_attr($align) . '" style="width: ' . $width . 'px;">'
. do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $caption . '</figcaption></figure>';
}
This alters the default output code, removing the additional 10 pixels, and changing the
div
to
figure
and the
p
to
figcaption
.
The code is pretty simple, but if you want it even easier,
here it is in plugin form.[foot]Absolutely no support is provided for this plugin.[/foot] Just unzip and install according to
the directions in the codex. If you're interested, you can also
make it better on Github.