WordPress Snippets at WPcustoms

Add ‘img-responsive’ class to images

If you are using bootstrap this may be a handy snippet to automatically add the bootstrap img-repsponsive class to your post images.


/**
 * Snippet Name: Add ‘img-responsive’ class to images
 * Snippet URL: http://www.wpcustoms.net/snippets/add-img-responsive-class-images/
 */
 function wpc_add_image_responsive_class( $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('/)/', '$1 ' . $classes . ' $2', $html);
  } else {
    $html = preg_replace('/()/', '$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','wpc_add_image_responsive_class',10 );
add_filter( 'post_thumbnail_html', 'wpc_add_image_responsive_class', 10 );


// end of snippet - remove bug text below