WordPress自动移除img的width、height和class属性

2017年4月6日 建站技术 浏览 3,335 抢沙发 A+

WordPress文章插入图片自动移除img的width、height、class属性

当我们在WordPress文章中插入图片附件的时候默认的图片代码为:

<img class="alignnone size-full wp-image-123" src="https://www.kimsom.com/uploads/images/2017/201704/20170406/1491456608.jpg" alt="https://www.kimsom.com/" width="454" height="260" />

其中图片img标签中就会有class、src、alt、width、height这些属性,其中src是图片的路径,alt是图片的描述有利于优化,所以class以及width、height对于一个优秀的WordPress主题来说是非常的多余和没有必要的,甚至会造成数据库的冗余等等。

解决方法

依然是通过在当前主题的functions.php中添加如下代码:

add_filter( 'post_thumbnail_html', 'kimsom_remove_images_attribute', 10 );
add_filter( 'image_send_to_editor', 'kimsom_remove_images_attribute', 10 );
function kimsom_remove_images_attribute( $html ) {
$html = preg_replace( '/width="(\d*)"\s+height="(\d*)"\s+class=\"[^\"]*\"/', "", $html );
$html = preg_replace( '/  /', "", $html );
return $html;
}

最终效果

通过添加以上解决方法中的代码到WordPress主题中,在WordPress文章中插入图片的时候代码就非常的简洁了,最终效果代码如下:

<img src="https://www.kimsom.com/uploads/images/2017/201704/20170406/1491456608.jpg" alt="https://www.kimsom.com/" />

是不是非常的干净了呢?当然如果某些WordPress主题作者开发的时候是通过图片css控制图片样式的,那么页面效果可能会有所变化,大家动手调试一下即可。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: