WordPress去除img标签高度宽度让图片自适应

在移动设备端,因为屏幕都比较小,如果要让图片自适应屏幕,我们应当把 width 和 height 属性去除,不然图片可能会比屏幕大,有此需求的朋友可以参考下本文,要求如下,在桌面设备上,图片使用的是以下的 HTML 代码:

<img src="abc.png" alt="abc" width="580" height="267" />

在移动设备端,因为屏幕都比较小,如果要让图片自适应屏幕,我们应当把 width 和 height 属性去除,不然图片可能会比屏幕大:

<img src="abc.png" alt="abc" />

方法一:

将下面代码复制到当前主题的 functions.php 文件中:

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;
}

方法二:

// 自适应图片删除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);
}

就这样试一下是不是达到想要的结果了。

http://xzh.i3geek.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,请不要用于商业用途及非法用途,否则后果自负!
3. 如果你也有好源码或者教程,可以到审核区发布,分享有金币奖励和额外收入!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,默认解压密码为"qq301.com",如遇到无法解压的请联系管理员!
资源客是一个优秀的分享资源站,本站资源均为各位友友分享而来,特殊原创会标明如有侵犯版权等可联系删除

资源客 » WordPress去除img标签高度宽度让图片自适应