6

WordPress如何移除文章图片的宽度和高度属性

 3 years ago
source link: https://www.huhexian.com/17761.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

WordPress如何移除文章图片的宽度和高度属性

2021-12-1714:17:57评论745字

我们在使用WordPress建站从后台媒体上传图片的时候,会默认添加图片的高度和宽度属性,我们有的时候可能需要移除文章图片的宽度和高度,以方便我们自己使用自定义CSS。很多朋友不知道如何修改或者删除文章图片的宽度和高度属性,下面就来给大家带来教程。

WordPress如何移除文章图片的宽度和高度属性

将下面的代码添加到主题的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;

测试上方代码可能发现这个代码只有在编辑文章通过插入媒体库的图片,而且不能添加图片标题和说明的情况下才有效,而且以前文章中图片的宽度和高度属性也无法移除。所以真正有效移除 WordPress 文章图片的宽度和高度属性的做法应该是将以下 JS 代码添加到页脚 footer.php 文件中即可:

  1. <script>
  2. $(document).ready(function() {
  3. $(".main_box img").removeAttr("width height");
  4. </script>

.single-content img 的意思就是文章内容中的图片,以上代码的意思也就是说只移除文章内容中的图片宽高度属性。记得将 .single-content 改为自己站点文章内容的 class 属性哦。

PS:也可以将以上 JS 代码添加到当前主题的主 JS 文件中。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK