Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress: remove inline width from captions
<?php
add_shortcode('wp_caption', 'fixed_img_caption_shortcode');
add_shortcode('caption', 'fixed_img_caption_shortcode');
function fixed_img_caption_shortcode($attr, $content = null) {
// New-style shortcode with the caption inside the shortcode with the link and image tags.
if ( ! isset( $attr['caption'] ) ) {
if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
$content = $matches[1];
$attr['caption'] = trim( $matches[2] );
}
}
// 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: auto">'
. do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
}
?>
@beeriz

This comment has been minimized.

Copy link

@beeriz beeriz commented Apr 6, 2018

This saved me from becoming insane, my wordpress stopped resizing pictures without changing anything.
I used this to remove width from caption, but now the text in caption lost its "styling", can I prevent this from happening?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment