I am using WordPress with Twitter Bootstrap 3 and have an issue when it comes to images with captions.
Images with captions are given a height and width attribute which stops them from being responsive.
I tried the following code below but this only works for images without captions:
function change_uploaded_image_html( $html ) {
// Removes height and width attribute from images when they
// are uploaded.
$classes = 'img-responsive';
if ( preg_match( '/<img.*? class=".*?" />/', $html ) ) {
$html = preg_replace( '/(<img.*? class=".*?)(".*?/>)/', '$1 ' . $classes . '$2', $html );
}
else {
$html = preg_replace( '/(<img.*?)/>/', '$1 class="' . $classes . '" />', $html );
}
$html = preg_replace( '/(height|width)="d*"s/', "", $html );
return $html;
}
I then tried another method from another post on this forum which sets the width attribute to nothing but I did not get any success as the width and height attribute on the image remains:
function my_img_caption_shortcode_filter( $val, $attr, $content=null ){
extract( shortcode_atts( array(
'id' => '',
'align' => '',
'width' => '',
'caption' => ''
), $attr ) );
if ( 1 > ( int ) $width || empty( $caption ) )
return $val;
$capid = '';
if ( $id ) {
$id = esc_attr( $id );
$capid = 'id="figcaption_'. $id . '" ';
$id = 'id="' . $id . '" aria-labelledby="figcaption_' . $id . '" ';
}
return '<figure ' . $id . 'class="wp-caption ' . esc_attr($align) . '" >'
. do_shortcode( $content ) . '<figcaption ' . $capid
. 'class="wp-caption-text">' . $caption . '</figcaption></figure>';
}
add_filter( 'img_caption_shortcode', 'my_img_caption_shortcode_filter',10 ,3 );
I am looking for a way to do this with PHP and WP’s in-built filters and I think I am close to the answer but do not know in which direction to go exactly.
Many Thanks,
nav
Here is another possibility, it alters the image markup when you select an image to add to your content in the editor
I used the below solution. It was found here
That’s a lot of code, if you want the image original size and not the cropped version why don’t you use
wp_get_attachment_image_src()
instead?In Reply to your comment:->
this worked for me, it it doesn’t for you, you may want to look at other hooks that are forcing the width on your images