Support » Plugins » Hacks » Stripping Inline Width Style for wp_caption on Images

  • WordPress adds a width attribute inline style for an image when a caption is used resulting in mark similar to :
    <div id="attachment_5" class="wp-caption alignnone" style="width: 280px">

    I want to globally strip these from my site and found a function on a few web sites:

    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>';
    }

    Problem is that the code doesn’t seem to work in 3.5.1 I believe it only works up to 3.4. Can anyone contribute to how it can be tweaked to work in the latest version?

    THanks

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    This is not a version issue. The only difference between your snippet and the default caption shortcode callback is the 10px padding was removed. If you remove the entire style portion from the return line, it should work for you. Note the dimensions for the actual image inserted by the media uploader still remain.

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

    hey cool, yes that works – mucho gracias!

    Thanks bcworkz! Mucho gracias indeed 🙂

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Stripping Inline Width Style for wp_caption on Images’ is closed to new replies.