wordpress 去除img标签中的width和height

对于响应式主题来说,img标签的width和height的尺寸和原始图片尺寸一样比较好说,若不一样,那么在自适应的屏幕下显示就十分鸡肋了,所以,在输出文章的时候进行过滤,把img标签中的width和height统统去除掉,已达到在响应式主题中显示比较完美。

源代码比较简单,用wordpress的钩子进行输出前的过滤,首先是正则获取文章中的img标签,放到一个数组里,然后对数组进行遍历循环,再次利用正则进行替换为空,这样就达到目的了。

方法

将以下代码放到主题的functions.php中就可实现。

// 自适应图片删除width和height,by Ludou
// 代码来自 http://www.ludou.org/wordpress-remove-images-width-height-attribute.html
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);
}