WordPress.org

Ready to get started?Download WordPress

Forums

Stripping Inline Width Style for wp_caption on Images (4 posts)

  1. gowrann
    Member
    Posted 1 year ago #

    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

  2. bcworkz
    Member
    Posted 1 year ago #

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

  3. gowrann
    Member
    Posted 1 year ago #

    hey cool, yes that works - mucho gracias!

  4. mattrock1
    Member
    Posted 1 year ago #

    Thanks bcworkz! Mucho gracias indeed :)

Topic Closed

This topic has been closed to new replies.

About this Topic