17

I want to make a responsive theme with Bootstrap 3. However, I need to automatically add the CSS class .img-responsive to every post image because I need the images to be responsive.

Please suggest me what I need to add in WordPress's functions.php file or any other file that will allow me to add the CSS class automatically.

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Amit Sarker
  • 319
  • 1
  • 3
  • 5

11 Answers11

43

since you need to have it for all of your post images, then you need to add a hook for the content and add

function add_responsive_class($content){

        $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
        $document = new DOMDocument();
        libxml_use_internal_errors(true);
        $document->loadHTML(utf8_decode($content));

        $imgs = $document->getElementsByTagName('img');
        foreach ($imgs as $img) {
           $img->setAttribute('class','img-responsive');
        }

        $html = $document->saveHTML();
        return $html;
}

now add the hook to the content

add_filter        ('the_content', 'add_responsive_class');

However, if you already have classes for the img and you need to add a new class then you can refer to PHP equivalent to jQuery addClass. Or, you can simply do this:

$existing_class = $img->getAttribute('class');
$img->setAttribute('class', "img-responsive $existing_class");

The code above works .. i use it to remove src and data-src for image lazy loading. Hope it works for you

friism
  • 19,068
  • 5
  • 80
  • 116
AhmadAssaf
  • 3,556
  • 5
  • 31
  • 42
  • 3
    Nice use of DOMDocument. I see way to many people suggesting the use of regex for this type of application. +1 – Greg L Oct 22 '14 at 00:23
  • 1
    regex is much faster than this. consider also doing it using javascript. With jquery, which I guess you ahve, would just be $("#main-content").find("img").addClass("img-responsive").. – chesscov77 Feb 27 '15 at 10:14
  • 3
    @Juan other people suggested having a JS solution as well and again the answer is that this means that the page has to be generated from PHP then this function will run on document load or any other hook you defined .. its better to have the classes in the generated PHP file, you will save unnecessary DOM manipulations that can be directly done on the backend and its extremely useful in cases where you do caching as well. Plus, responsive images can be achieved via CSS and doing that using jQuery as you suggested solution requires JS to be enabled which might not be always the case for some – AhmadAssaf Feb 27 '15 at 10:20
  • @AhmadAssaf js disabled in 2015? really? Plus, the question clearly is "how to add a class to my img elements inside my post". The question suggests he needs code to be placed in functions.php, but thats just because he was lost..you dont event need jquery for this. – chesscov77 Feb 28 '15 at 12:01
  • 1
    @Juan you'd be surprised on how many disable it for various reasons. A good pegrammer doesn't assume stuff but design to catch all the cases, that's the principle of progressive enhancements. Also, how do you know he was "lost" ? Can you read minds. Anyhow, there is no one perfect solution but you were assuming so many stuff in your comment – AhmadAssaf Feb 28 '15 at 12:49
  • 1
    This solution causes the `the_content()` function to wrap the post contents with `` and `` tags. – LondonAppDev Mar 08 '15 at 11:51
  • I'm getting a warning when the content is empty (Warning: DOMDocument::loadHTML(): Empty string supplied as input). Any way to suppress that? – Teo Maragakis Jul 01 '15 at 09:28
  • @TeoMaragakis check for empty content before and only enter if `$content` is not empty – AhmadAssaf Jul 01 '15 at 16:15
  • 1
    To avoid adding and - use this $html->loadHTML(utf8_decode($content), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); – Kref May 16 '16 at 10:14
  • Works perfectly with the `lazysizes` library for lazy loading. And I'm glad it was on this question because it was the first thing I search for. – vhs Apr 17 '17 at 18:26
  • For better performance and functionality, consider adding an early termination based on some of the WP guidance for `the_content`: https://developer.wordpress.org/reference/hooks/the_content/ – vhs Apr 18 '17 at 05:36
  • this is not a best answer, using DOMDocument is overkill and slow and not necessary – OzzyCzech Jul 26 '18 at 09:02
  • its no eligible answer see @Yaron s answer instead – niklas Nov 13 '18 at 21:00
  • this is not working on block editor – Netlog Sep 29 '21 at 16:25
29

This approach is better: https://wordpress.stackexchange.com/questions/108831/add-css-class-to-every-image

function add_image_class($class){
    $class .= ' additional-class';
    return $class;
}
add_filter('get_image_tag_class','add_image_class');

Only caveat is that it adds the class within the edit pane when you insert new images and doesn't affect pre existing ones.

Community
  • 1
  • 1
Yaron
  • 1,867
  • 20
  • 16
15

I think the easiest way is to use CSS like this.

.content img { height: auto; max-width: 100%; }

Where .content is the area that contains your post content.

Note: You may also want to override the .wp-caption class as well like so.

.wp-caption { width: auto !important; }
Syclone
  • 1,235
  • 13
  • 14
  • 1
    This should be the correct answer. Wrap the entire content in a `div` and add a class to it called `content` or whatever you want to call it. – Edward Sep 11 '17 at 00:49
  • sigh. Just because you have a different method than OP, doesn't mean you're right. You can have an opinion, but put that in a comment to the question instead, because this answer is simply off-topic. – InanisAtheos Jul 19 '19 at 21:21
  • @PatrikAlienus How is this off-topic? The aim is to make all images within the post responsive. The CSS in my answer will make every image in the post responsive. No need to add a class to every image if we know the selector for all images. This solution used less code and does not require server processing. – Syclone Jul 21 '19 at 01:15
  • @Syclone He's asking specifically how to automatically add a specific class to images, thus this answer is off-topic. – InanisAtheos Jul 22 '19 at 18:39
  • @Syclone He's letting you know of his intention, that's true. However only after that, does he ask a specific question. I believe your answer is off-topic because of this, not because your solution is worse. It's not most of the time, but you can't know every detail of OP's environment, thus you should refrain from straying away from the actual question. THAT is actually quite important here as Q&A's are meant to serve many, not just one. – InanisAtheos Jul 25 '19 at 22:24
  • @PatrikAlienus Solution servers many and can be used for many scenarios other than responsive purposes. I think we can agree to disagree. – Syclone Jul 25 '19 at 23:18
13

I had the same question, and adding this function to functions.php worked for me.

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');
user793487
  • 151
  • 2
  • 5
  • This answer should be marked as solved, because this works much better than others. This dont insert DOCTYPE, HTML and BODY tags inside the html. – Diego Somar Nov 06 '17 at 12:47
  • This particular code not only work perfectly. It allows you to enable global modal images on the popular theme newsletter and newsmag. The global modal ON is broken on their theme when you enable any CDN. With this piece of coded added to a plugin, the theme restores the functionality. They should hire you to improve their code as they are using wp-booster and they don't want to fix it, they just say "CDN may not work outside of Cloudflare. – Alex Vojacek Apr 17 '18 at 20:12
5

When you display post in your loop, you could do :

the_post_thumbnail('thumbnail', array('class' => 'img-responsive'));

See https://codex.wordpress.org/Function_Reference/the_post_thumbnail for more details.

Bertrand
  • 1,000
  • 1
  • 9
  • 20
  • Thanks Bertrand, But I need all of my post images will full responsive. So, I want to add class="img-responsive" for all post images. – Amit Sarker Dec 09 '13 at 19:51
3

Not quite sure how good this answer is performance wise but it works. Just put this in functions.php.

function img_responsive($content){
    return str_replace('<img class="','<img class="img-responsive ',$content);
}
add_filter('the_content','img_responsive');

Please note that you need the space after class="img-responsive so it doesn't merge with other classes.

Lallex
  • 100
  • 4
2

You can use jquery code on the header.php file of your theme.

jQuery(function() {
  jQuery(img).addClass('img-responsive');
});
  • please note that this is a JS solution .. which means that the page has to be generated from PHP then this function will run on document load or any other hook you defined .. its better to have the classes in the generated PHP file – AhmadAssaf Dec 10 '13 at 16:31
  • its not ideal or professional way. Good solution is using filters – Mohammad Ayoub Khan Jun 10 '21 at 10:44
1

I think you don't require to add class to make image responsive. just remove height width from featured image, image will become responsive definitely.

There is code put in your function.php to remove height width

add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10, 3 );

function remove_thumbnail_dimensions( $html, $post_id, $post_image_id ) {
    $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
    return $html;
} 
Mitul Shah
  • 1,556
  • 1
  • 12
  • 34
  • Mitul, I have removed width and height from post images by using your codes. It really helpful. But It is not make post images responsive in Bootstrap 3.0 – Amit Sarker Dec 09 '13 at 19:55
0

Classes are not added on upload, but when the image is sent to the editor. You can use the image_send_to_editor filter to add one or more classes. This example adds a fancybox class.

Community
  • 1
  • 1
diggy
  • 6,748
  • 2
  • 18
  • 24
0
//all classes i need in a string

$classes = 'img-responsive attachment-post-thumbnail size-post-thumbnail wp-post-image'; 

//then i use my variable

the_post_thumbnail('post_thumbnail', array( 'class' => $classes ));
0

You could just make all images responsive in the css as mentioned here:

I want to apply css class(bootstrap) .img-responsive on all content images

That uses LESS, but the Sass version is pretty much the same:

  img {
    @include img-responsive();
  }
Community
  • 1
  • 1