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]))[‘|””].*?[/]?>/””

标签

发表评论