How to add automatic class in image for wordpress

2019-01-10 21:38发布

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.

11条回答
Deceive 欺骗
2楼-- · 2019-01-10 22:13

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.

查看更多
Root(大扎)
3楼-- · 2019-01-10 22:15

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

jQuery(function() {
  jQuery(img).addClass('img-responsive');
});
查看更多
男人必须洒脱
4楼-- · 2019-01-10 22:20

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

查看更多
成全新的幸福
5楼-- · 2019-01-10 22:23
//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 ));
查看更多
我命由我不由天
6楼-- · 2019-01-10 22:25

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.

查看更多
登录 后发表回答