网上流传移除 WordPress 文章图片的宽度和高度属性的做法都是添加以下代码到当前主题的 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;
- }
但是经过本人反复测试发现这个代码只有在编辑文章通过插入媒体库的图片,而且不能添加图片标题和说明的情况下才有效,而且以前文章中图片的宽度和高度属性也无法移除。所以真正有效移除 WordPress 文章图片的宽度和高度属性的做法应该是将以下 JS 代码添加到页脚 footer.php 文件中即可:
- <script>
- $(document).ready(function() {
- $(“.single-content img”).removeAttr(“width height”);
- });
- </script>
说明:.single-content img 的意思就是文章内容中的图片,以上代码的意思也就是说只移除文章内容中的图片宽高度属性。记得将 .single-content 改为自己站点文章内容的 class 属性哦。PS:也可以将以上 JS 代码添加到当前主题的主 JS 文件中。