Make images in post or page responsive automatically

Hello there!
I’ve just found how to make all the images responsive automatically when inserting into the post of page. It works for me, so maybe it will help to anyone.
You should put this code to custom.php:

// responsive images auto class
function add_image_responsive_class($content) {
   global $post;
   $pattern ="/<img(.*?)class=\"(.*?)\"(.*?)>/i";
   $replacement = '<img$1class="$2 img-responsive"$3>';
   $content = preg_replace($pattern, $replacement, $content);
   return $content;
add_filter('the_content', 'add_image_responsive_class');

So now if you insert full-size image into the post, it will fill the full width of post container.

1 Like

@ierhyna you really made my day.
Thank you so much for the snippet :smile: it helped me a lot

@omar_gourari You are welcome :slight_smile:


You don’t need to add a filter for this, you can do this purely in the less,

.content {
   img.size-full {

Adding this to your app.less will apply the bootstrap img-responsive mixin styles to any image in the content div with a class of .size-full


@Podders Wow! Thanks a lot. Very cute decision!
UPD. Maybe it should be .img-responsive(); with comma? Either I get “unrecognized input” error.

Whoops, my bad, yes you need a dot at the start of the mixin call, i’ve amended my original reply to reflect this :slight_smile:

You could use jquery in the _main.js file



in the common function - line 23

var Roots = {
// All pages
common: {
init: function() {
  // JavaScript to be fired on all pages





This worked a treat for me…

Neil from Bristol, England

JS isn’t the right tool for this job. You want to either add the classes with PHP, or handle the styling in your LESS.

That doesn’t address the hard coded width and height that Wordpress adds in the editor (why it does that in a responsive world is beyond me!). So I used the following

  $pattern ="/<img(.*?)class=\"(.*?)\"(.*?)width=\".*?\" height=\".*?\"(.*?)>/i";
  $replacement = '<img$1class="$2 img-responsive"$3 $4>';

Now I have noticed that some posts also have [caption.... width="500" markup in the editor which turns into <"width:'500px'" in the rendered page. All this filtering seems very second best - is there a better way?