wordpress手机版文章图片自适应方法

wordpress手机版文章图片自适应方法

在编辑文章时,插入的图片,系统会自动添加宽和高,这样在手机版中不好自适应.

通过查找wordpress的相关函数,发现可以通过在输出前进行过滤.

代码实现方法如下:

// 自适应图片删除width和height
function 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', 'remove_width_height_attribute', 99);
}
//add_filter( 'post_thumbnail_html', 'remove_width_height_attribute', 10 );//删除后台缩略图代码中img的width和height属性
//add_filter( 'image_send_to_editor', 'remove_width_height_attribute', 10 );//删除后台插入缩略图代码中img的width和height属性

 

当然,也可以在插入图片时去除图片的宽度和高度,不过,这样的话,电脑版的图片也不好控制.所以我这里不进行处理.

如果你需要在插入时去除,可以把代码中最后两行注释去掉,即可.