年前折腾了一下博客的自适应功能,让使用手机、iPad等移动设备的访客也能顺畅的浏览露兜博客的内容。这里分享一下自适应主题需要用到的一个功能:当访客使用手机访问时,自动删除文章内容中图片的width和height属性,以达到自适应的效果。
如,在桌面设备上,图片使用的是以下的HTML代码:
<img src="abc.png" alt="abc" width="580" height="267" />
在移动设备端,因为屏幕都比较小,如果要让图片自适应屏幕,我们应当把width和height属性去除,不然图片可能会比屏幕大:
<img src="abc.png" alt="abc" />
为了达到此目的,在当前主题的functions.php中加入以下PHP代码即可:
// 自适应图片删除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); }
文章来源:https://www.ludou.org/wordpress-remove-images-width-height-attribute.html