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条回答
冷血范
2楼-- · 2019-01-10 21:59

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; }
查看更多
我命由我不由天
3楼-- · 2019-01-10 22:00

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.

查看更多
干净又极端
4楼-- · 2019-01-10 22:01

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');
查看更多
乱世女痞
5楼-- · 2019-01-10 22:02

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.

查看更多
小情绪 Triste *
6楼-- · 2019-01-10 22:06

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();
  }
查看更多
混吃等死
7楼-- · 2019-01-10 22:07

I think you don't require to add class to make image responsive. just remove height width from featured image, image will become responsive definitely.

There is code put in your function.php to remove height width

add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10, 3 );

function remove_thumbnail_dimensions( $html, $post_id, $post_image_id ) {
    $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
    return $html;
} 
查看更多
登录 后发表回答