Make post images resonsive

I want to make my post images responsive by adding the class ‘img-responsive’.

I could use jQuery to find the img and add that class, but I also found a php approach that looks interesting and I think would slightly increase load time.

// Add responsive class to all images
// http://stackoverflow.com/questions/20473004/how-to-add-automatic-class-in-image-for-wordpress-post
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) {           
          $existing_class = $img->getAttribute('class');
                    $img->setAttribute('class', "img-responsive $existing_class");
        }

        $html = $document->saveHTML();
        return $html;   
}
add_filter('the_content', __NAMESPACE__ . '\\add_responsive_class');


But I’m getting an error:

Fatal error:  Class 'Roots\Sage\Extras\DOMDocument' not found 

I’ve confimed that the extenstion is available by putting this in the index file:

$document = new DOMDocument();
print_r($document);

Is there some way of dealing with the Namespacing that I’m missing?

Seems like you’re complicating things. Why wouldn’t you just use Sass? Extend the .img-responsive class to something like .hentry img

2 Likes

Because I am an idiot is why. :grinning:

Thanks, @ben.

.hentry img {
    @extend .img-responsive;
}