Improved HTML5 WordPress Captions.

Published in: Web Development.

The current1 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.2 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:

  1. Removing the extra 10pixels to open up image/captions to easier external CSS control,3 and
  2. replacing the div based structure with semantic HTML5 figure/figcaption structure.4

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.5 Just unzip and install according to the directions in the codex. If you’re interested, you can also make it better on Github.

  1. version 3.2.1
  2. If you know, please enlighten me.
  3. 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.
  4. This structure is so wonderfully semantic, and is frequently appropriate.
  5. Absolutely no support is provided for this plugin.

Share:

Permalink:
http://writings.orangegnome.com/writes/improved-html5-wordpress-captions/
Shortlink:
http://lilgn.me/4l

Pingbacks:

Comments are disabled on this blog. If you have a thought, contact me on Twitter or on the contact form. If you have a really long thought, send me a link to your post about it.