WordPress教程

WordPress去除img标签height/width高度宽度让图片自适应

阿里云

在移动设备端,因为屏幕都比较小,如果要让图片自适应屏幕,我们应当把 width 和 height 属性去除,不然图片可能会比屏幕大,有此需求的朋友可以参考下本文,要求如下,在桌面设备上,图片使用的是以下的 HTML 代码:

  1. <img src="abc.png" alt="abc" width="580" height="267" />
也想出现在这里?联系我们
创客主机

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

  1. <img src="abc.png" alt="abc" />

方法一:

将下面代码复制到当前主题的 functions.php 文件中:

  1. add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
  2. add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
  3. function remove_width_attribute( $html ) {
  4. $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
  5. return $html;
  6. }

方法二:

  1. // 自适应图片删除width和height,by Ludou
  2. function ludou_remove_width_height_attribute($content){
  3. preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png\.bmp]))[\'|\"].*?[\/]?>/", $content, $images);
  4. if(!empty($images)) {
  5. foreach($images[0] as $index => $value){
  6. $new_img = preg_replace('/(width|height)="\d*"\s/', "", $images[0][$index]);
  7. $content = str_replace($images[0][$index], $new_img, $content);
  8. }
  9. }
  10. return $content;
  11. }
  12. // 判断是否是移动设备浏览
  13. if(wp_is_mobile()) {
  14. // 删除文章内容中img的width和height属性
  15. add_filter('the_content', 'ludou_remove_width_height_attribute', 99);
  16. }

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

WordPress 去除 img 标签 height/width 高度宽度让图片自适应

已有 428 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!