1

I already have a wordpress website with many images in posts. I'm creating a new theme using bootstrap but it seems like the images are crossing the container area.

Bootstrap provides a built-in class :

class="img-responsive"

but this code needs to be inserted in all the <img> tags which is a lot of work. What is the other way to make the images responsive?

Also, this code doesn't work -

img
{
     border: 0 none;
     max-width: 100%;
     vertical-align: middle;
}

It just squeezes the image inwards.

Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71
  • Checkout this answer: https://stackoverflow.com/questions/20473004/how-to-add-automatic-class-in-image-for-wordpress-post/28050686#28050686 – Syclone Oct 04 '17 at 00:40

1 Answers1

3

There is a gist showing how to do this at https://gist.github.com/mkdizajn/7352469

The technique is to add the following to your functions.php (from gist):

function bootstrap_responsive_images( $html ){
    $classes = 'img-responsive'; // separated by spaces, e.g. 'img image-link'
    // check if there are already classes assigned to the anchor
    if ( preg_match('/<img.*? class="/', $html) ) {
        $html = preg_replace('/(<img.*? class=".*?)(".*?\/>)/', '$1 ' . $classes . ' $2', $html);
    } else {
        $html = preg_replace('/(<img.*?)(\/>)/', '$1 class="' . $classes . '" $2', $html);
    }
    // remove dimensions from images,, does not need it!
    $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
    return $html;
}
add_filter( 'the_content','bootstrap_responsive_images',10 );
add_filter( 'post_thumbnail_html', 'bootstrap_responsive_images', 10 ); 

You should consider creating a child theme to make this modification if you are using a stock theme.

Vinicius Garcia
  • 1,740
  • 4
  • 30
  • 54
Jeff Paquette
  • 7,089
  • 2
  • 31
  • 40