How to add automatic class in image for wordpress post

43,962

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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

Solution 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.

Share:
43,962
Amit Sarker
Author by

Amit Sarker

Updated on January 13, 2020

Comments

  • Amit Sarker
    Amit Sarker over 4 years

    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.

  • AhmadAssaf
    AhmadAssaf over 10 years
    this hook works for newly added images .. but will not work on his old posts
  • diggy
    diggy over 10 years
    Correct. Note that the OP is creating a new theme.
  • Amit Sarker
    Amit Sarker over 10 years
    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
    Amit Sarker over 10 years
    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
  • AhmadAssaf
    AhmadAssaf over 10 years
    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
  • Greg L
    Greg L over 9 years
    Nice use of DOMDocument. I see way to many people suggesting the use of regex for this type of application. +1
  • Juan
    Juan about 9 years
    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")..
  • AhmadAssaf
    AhmadAssaf about 9 years
    @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
  • Juan
    Juan about 9 years
    @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.
  • AhmadAssaf
    AhmadAssaf about 9 years
    @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
  • LondonAppDev
    LondonAppDev about 9 years
    This solution causes the the_content() function to wrap the post contents with <html> and <body> tags.
  • Teo Maragakis
    Teo Maragakis almost 9 years
    I'm getting a warning when the content is empty (Warning: DOMDocument::loadHTML(): Empty string supplied as input). Any way to suppress that?
  • AhmadAssaf
    AhmadAssaf almost 9 years
    @TeoMaragakis check for empty content before and only enter if $content is not empty
  • Kref
    Kref almost 8 years
    To avoid adding <html> and <body> - use this $html->loadHTML(utf8_decode($content), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  • erginduran
    erginduran almost 8 years
    this answer is better than others.It should be marked as the correct answer.
  • JoeMoe1984
    JoeMoe1984 almost 8 years
    I personally like this answer the best. Easiest to add classes to an image being added.
  • vhs
    vhs about 7 years
    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
    vhs about 7 years
    For better performance and functionality, consider adding an early termination based on some of the WP guidance for the_content: developer.wordpress.org/reference/hooks/the_content
  • Edward
    Edward over 6 years
    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.
  • Diego Somar
    Diego Somar over 6 years
    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.
  • Alex Vojacek
    Alex Vojacek about 6 years
    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.
  • ACJ
    ACJ almost 6 years
    I’d say this is “the WordPress way” to go about this.
  • OzzyCzech
    OzzyCzech almost 6 years
    best answer from all
  • OzzyCzech
    OzzyCzech almost 6 years
    this is not a best answer, using DOMDocument is overkill and slow and not necessary
  • niklas
    niklas over 5 years
    its no eligible answer see @Yaron s answer instead
  • Paweł Tomkiel
    Paweł Tomkiel over 5 years
    And what if class isn't the first attribute?
  • InanisAtheos
    InanisAtheos almost 5 years
    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.
  • Syclone
    Syclone almost 5 years
    @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.
  • InanisAtheos
    InanisAtheos almost 5 years
    @Syclone He's asking specifically how to automatically add a specific class to images, thus this answer is off-topic.
  • InanisAtheos
    InanisAtheos almost 5 years
    @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.
  • Syclone
    Syclone almost 5 years
    @PatrikAlienus Solution servers many and can be used for many scenarios other than responsive purposes. I think we can agree to disagree.
  • Mohammad Ayoub Khan
    Mohammad Ayoub Khan almost 3 years
    its not ideal or professional way. Good solution is using filters
  • Netlog
    Netlog over 2 years
    this is not working on block editor
  • Netlog
    Netlog over 2 years
    this is not working on block editor