WordPress去除图片img标签默认的高和度
PHP #wordpress2014-03-19 09:32
现在是多终端时代,常常在桌面设备上,图片使用的是以下的HTML代码:
<img src="yige.org.png" alt="yige.org" width="111" height="111" />
在移动设备端,因为屏幕都比较小,如果要让图片自适应屏幕,我们应当把width和height属性去除,不然图片可能会比屏幕大:
<img src="yige.org.png" alt="yige.org" />
方法一
将下面代码复制到当前主题的 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
function yige_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', 'yige_remove_width_height_attribute', 99);
}相关文章
- PHP多种方式发送POST请求 2014/02/17
- PHP根据日期判断星座的函数 2013/03/22
- PHP显示搜索引擎来的关键词的函数 2013/03/21
- PHP记录用户通过搜索引擎进网站的关键词代码 2013/03/21
- 错误 Class 'SoapClient' not found in PHP 解决方法 2013/02/27
- PHP根据ISBN获取图书的方法 2013/01/14
- smarty中时间格式化函数date_format 2012/12/28
- PHP防注入安全代码 2012/12/21
- eval()一个有意思的PHP函数 2012/12/21
- php的免杀小马 2012/12/21