Remove Automatically Generated Inline Style on Images with Caption in WordPress
For some strange reason images inserted in posts or pages in WordPress will automatically have an inline style applied to them, which could cause formatting headaches for the site visitor. The following is a simple piece of code that you can add to your theme’s functions.php file to fix this problem:
add_shortcode('wp_caption', 'fixed_img_caption_shortcode');
add_shortcode('caption', 'fixed_img_caption_shortcode');
function fixed_img_caption_shortcode($attr, $content = null) {
// Allow plugins/themes to override the default caption template.
$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: ' . ((int) $width) . 'px">'
. do_shortcode( $content ) . '<p>'
. $caption . '</p></div>';
}
6 Comments
i use it, but it does’t work, my wordpress is 3.0.1
Do you have an example of where it’s not working?
I’m having trouble with this. I’m using featured images as alternative header images on each page. I want top control their style from my stylesheet but WordPress inserts inline style. I copied your code into my functions.php file but it didn’t work. I’m editing the twentyten theme on version 3.1.2.
Any help would be greatly appreciated. Thanks
I know this works fine on images within the body of a post or page, as it’s fine on this site, but not sure how it applies to featured images. If you have a link that you can provide I’ll take a look when I get some time.
Troy, it did not work for me. Sorry. I found very similar code that works at:
http://wp-snippets.com/1016/remove-default-inline-style-of-wp-caption/
I did not take time to figure out what is different between yours and the other, but there must be a typo in yours?
Thanks Eddie. I’m not sure why it didn’t work for you, the item you mention from WP-Snippets references me and this post as its source therefore it is the same code as mine above.
One Trackback
[...] http://troychaplin.ca/blog/wordpress-functions/remove-automatically-generated-inline-style-on-images… Tweet Discussion /** * var disqus_identifier; [Optional but recommended: Define a unique [...]