Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
315 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...