Last Updated: February 25, 2016
·
3.525K
· Kresimir Pendic

Wordpress responsive images!

I'm using this function to have my images ready for responsive layout. I use bootstrap for presentation layout.. but you can sure use your own css ofcorse!

//----------------------------------------------------------/
//  responsive images [ 1) add img-responsive class 2) remove dimensions ]
//----------------------------------------------------------/

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

For the code sake this is what goes on in here..

I'm appending the "img-responsive" class to all images, that class is bootstraps class for images that have max-width:100% and will correctly shrink on smaller device .. and secondly, I remove w|h from the tag also.. do not need that part :o|

hth someone, cose I did loose some time with this one :)

cheers

3 Responses
Add your response

Nice!

over 1 year ago ·

Parsing html with regular expressions has several problems, for example you don't handle single quotes.

Here's a solution using http://simplehtmldom.sourceforge.net/

require 'include/simple_html_dom.php';
 function bootstrap_responsive_images( $html ){
  $classes = ['img-responsive'];

  $dom = str_get_html($html);
  foreach($dom->find('img') as $img) {
    $img_classes = explode(" ", $img->class);
    $img_classes = array_unique(array_merge($img_classes, $classes));
    $img->classes = implode(" ", $img_classes);

    $img->width = null;
    $img->height = null;
  }

  return (string) $dom;
}
over 1 year ago ·

@voidus,

thanks for great comment, and also cool class,, this simplehtmldom looks great!

cheers

over 1 year ago ·