禁止WordPress图片自动添加width和height属性

WordPress文章中从媒体库插入图片的时候,img标签会自动添加width和height属性,下面的HTML代码就是在插入图片时自动添加的高度和宽度属性。这样的话,图片可能就会变形。影响阅读体验,尤其是在手机上,图片超过屏幕大小,影响文章的整体性和可读性。

<img src="https://lerm.net/lerm/wp-content/uploads/2015/11/child-abduction.jpg" alt="child abduction" width="1022" height="489" class="aligncenter size-full wp-image-512" />

如何解决这个问题,使文章中的图片自适性屏幕大小,以及我们可以用两种方法实现,

方法一

在后台WordPress主题编辑模板函数(functions.php)文件,在文件最后面添加如下代码:

//移除img标签自动高度和宽度。
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
function remove_width_attribute( $html ) {
  $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
  return $html;
} 

方法二

这种方法就是首先判断是否为移动设备,如果是移动设备就删除img标签的width和height属性,从而实现自适性的目的。

// 自适应图片删除width和height,by Ludou
function ludou_remove_width_height_attribute($content){
  preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png\.bmp]))[\'|\"].*?[\/]?>/", $content, $images);
  if(!empty($images)) {
    foreach($images[0] as $index => $value){
      $new_img = preg_replace('/(width|height)="\d*"\s/', "", $images[0][$index]);
      $content = str_replace($images[0][$index], $new_img, $content);
    }
  }
  return $content;
}
// 判断是否是移动设备浏览
if(wp_is_mobile()) {
// 删除文章内容中img的width和height属性
  add_filter('the_content', 'ludou_remove_width_height_attribute', 99);
} 

现在看看文章中的图片是否是我们想要的效果。(via脚本之家)。

乐朦也是入坑不久的新手,如果有什么不对的地方请各位朋友留言指教,我会虚心接受,感谢各位的帮助。

发表评论

游客欢迎您123

“禁止WordPress图片自动添加width和height属性” 有 4条评论

  1. 为图像指定 height 和 width 属性是一个好习惯。如果设置了这些属性,就可以在页面加载时为图像预留空间。如果没有这些属性,浏览器就无法了解图像的尺寸,也就无法为图像保留合适的空间,因此当图像加载时,页面的布局就会发生变化。见http://www.w3school.com.cn/tags/att_img_height-width.asp
    不用删除width和height,而使用CSS来达到图片自适应的方法,用法更简单,更科学。见http://www.ludou.org/wordpress-remove-images-width-height-attribute.html#comment-12919

    • 嗯,仔细看了一下,确实是这样的,在css中指定图片的max-width:100%,height:auto图片就会出现响应式的效果,这样的话去除和不去除width和height效果都一样。

  2. 立秋之日,我点击整个秋天,搜索到丰收的画面;我打开我的手机,编辑最美的心愿;发送给你最好的祝愿:愿你存储快乐每一天,备份幸福整个秋天!

  3. 祖国花朵的绚丽,青梅竹马的回忆,纯洁天真的童趣,两小无猜的情意,如歌岁月的旋律,多彩人生的足迹,儿童节愿你童心童趣常相伴,开心快乐天天随