WordPress去除img标签的高度与宽度让图片自适应屏幕


本文整理自网络,侵删。

要求

如,在桌面设备上,图片使用的是以下的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);
}

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

标签:WordPress

相关阅读 >>

加速wordpress技巧redis缓存输出的html页面

wordpress中给媒体文件添加分类和标签的php功能实现

nginx设置wordpress伪静态的方法示例

wordpress中删除垃圾评论的方法

wysiwyg web builder 17激活教程 附汉化步骤

wordpress 2.8的8个特色的新增功能

nginx环境下wordpress的多站点功能配置详解

允许 wordpress 上传任意文件的方法

基于vue.js与wordpress rest api构建单页应用详解

wordpress升级后密码正确后台无法登陆的解决方法

更多相关阅读请进入《wordpress》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...