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 i
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
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();
}
//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 ));
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');
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.
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; }