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

问题分析
WordPress 文章插入图片附件的时候默认类似于以下的代码:

<img class="alignnone size-full wp-image-123" src="https://www.172u.cn/uploads/2018/11/F.png" alt="Fanly MIP" width="390" height="260" />

其中图片 img 标签中就会有 class、src、alt、width、height 这些属性,其中 src 是图片的路径,alt 是图片的描述有利于优化,所以 class 以及 width、height 对于一个优秀的 WordPress 主题来说是非常的多余和没有必要的,甚至会造成数据库的冗余等等。
解决方法
依然是通过在当前主题的 functions.php 中添加如下代码:

//remove insert images attribute
//add_filter( 'the_content', 'fanly_remove_images_attribute', 99 );
add_filter( 'post_thumbnail_html', 'fanly_remove_images_attribute', 10 );
add_filter( 'image_send_to_editor', 'fanly_remove_images_attribute', 10 );
function fanly_remove_images_attribute( $html ) {
        //$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
        $html = preg_replace( '/width="(\d*)"\s+height="(\d*)"\s+class="[^"]*"/', "", $html );
        $html = preg_replace( '/  /', "", $html );
        return $html;
}

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

<img src="https://www.172u.cn/uploads/2018/11/F.png"  />

此处评论已关闭