Troy Chaplin

Design & Development

Posted in the Blog

Fix Automatically Generated Inline Style on WordPress Image Captions

A couple of years ago I wrote a post that provides a function that will fix an automatically generated inline style on images with captions in WordPress. After recently building a new project with the 3.4 beta, and upgrading along the way, I noticed that this function no longer fixes the problem. I needed to get this problem fixed as the inline style caused issue with some areas of the overall layout, so with the aid of a colleague we discovered there was a small change in the core and we rewrote the function.

I’m still not quite sure why this exists in WordPress, but if you are running a site on 3.4 or above and need to fix this problem simply insert the following code into your functions.php file and you’ll be good to go!


add_shortcode('wp_caption', 'fixed_img_caption_shortcode');
add_shortcode('caption', 'fixed_img_caption_shortcode');
function fixed_img_caption_shortcode($attr, $content = null) {
	if ( ! isset( $attr['caption'] ) ) {
		if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
			$content = $matches[1];
			$attr['caption'] = trim( $matches[2] );
		}
	}
	$output = apply_filters('img_caption_shortcode', '', $attr, $content);
	if ( $output != '' )
		return $output;
	extract(shortcode_atts(array(
		'id'	=> '',
		'align'	=> 'alignnone',
		'width'	=> '',
		'caption' => ''
	), $attr));
	if ( 1 > (int) $width || empty($caption) )
		return $content;
	if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
	return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . $width . 'px">'
	. do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
}

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>