查看: 58|回复: 0

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

[复制链接]

2

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2010-9-17
发表于 2023-10-16 00:00:00 | 显示全部楼层 |阅读模式

要求 

如,在桌面设备上,图片使用的是以下的HTML代码: 

复制代码

代码如下:


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

复制代码

代码如下:


<img src="abc.png" /> 方法一, 
将下面代码复制到当前主题的 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); 


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

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部