Techie Turmoil

Get rid of caption inline styles in Wordpress

3rd March 2011

For some stupid reason, Wordpress injects an inline style to its image caption divs, setting the width to 10px larger than the enclosed image. This is wrong in so many ways:

  1. You should never use inline styles.
  2. Wordpress normally leaves styling to the themes (as it should).
  3. Even if you wanted this behaviour, padding would have been more appropriate. So how do we fix it? Well I just spent a while searching and found a few ill thought out suggestions, like overriding the style with !important (doesn't work on all browsers and could cause problems if you want to override it again in a specific class) or replacing the shortcode function, either directly in wp-includes/media.php (just plain crazy) or in your functions.php (better but doesn't work too well and not very maintainable). This last idea did lead me to find a good solution though. The img_caption_shortcode function has a filter, which effectively overrides its own output. So here's what I used (tested on WP 3.1):
add_filter( 'img_caption_shortcode', 'my_img_caption', 10, 3 );

function my_img_caption( $nowt, $attr, $content )
{
    extract( shortcode_atts( array(
        'id' => '',
        'align' => 'alignnone',
        'width' => '',
        'caption' => '',
    ), $attr ) );

    if ( empty( $caption ) )
        return $content;

    if ( $id )
        $id = 'id="' . esc_attr( $id ) . '" ';

    return '<div ' . $id . 'class="wp-caption ' . esc_attr( $align ) .
        '">' . do_shortcode( $content ) . '<p class="wp-caption-text">' .
        $caption . '</p></div>';
}

Shove that in your theme's functions.php and it will replace the core caption function, with the inline style removed. If you're wondering what the $nowt variable is about, it is an unused blank string passed by the filter.