如何通过functions.php阻止WordPress编辑器添加额外类与属性
当然可以通过主题的functions.php文件来搞定这些冗余代码的问题!我给你整理了几个精准的代码片段,直接复制粘贴到你的主题functions.php里就行(记得先备份文件,避免操作失误):
1. 移除图片的冗余类与固定宽高属性
这个函数会过滤WordPress输出的附件图片属性,直接清除掉alignnone、size-full、wp-image-xxx这类类名,同时删掉固定的width和height属性:
// 移除图片的冗余类和固定宽高属性 function remove_image_attributes($attrs) { // 清除所有图片类 unset($attrs['class']); // 移除固定宽高属性 unset($attrs['width']); unset($attrs['height']); return $attrs; } add_filter('wp_get_attachment_image_attributes', 'remove_image_attributes');
2. 处理编辑器插入图片的输出
上面的代码针对的是后台调用附件图片的场景,如果你是在编辑器里直接插入图片,还需要这个函数来清理编辑器生成的HTML:
// 清理编辑器插入图片时的冗余代码 function clean_image_editor_output($html, $id, $caption, $title, $align, $url, $size, $alt) { // 移除align开头的类 $html = preg_replace('/align\w+/', '', $html); // 移除size开头的类 $html = preg_replace('/size-\w+/', '', $html); // 移除wp-image-xxx类 $html = preg_replace('/wp-image-\d+/', '', $html); // 移除固定宽高属性 $html = preg_replace('/(width|height)="\d+"\s/', '', $html); // 清理多余的空格 $html = preg_replace('/\s+/', ' ', $html); return $html; } add_filter('image_send_to_editor', 'clean_image_editor_output', 10, 8);
3. 全局禁用自动添加宽高属性(WordPress 5.5+)
如果你的WordPress版本是5.5及以上,还可以用这个更简单的全局过滤器,直接阻止系统自动给图片加宽高:
// 全局禁用图片自动添加width和height属性 add_filter('img_tag_add_width_and_height', '__return_false');
最后补个CSS小提示
为了确保图片缩放时保持比例,建议在你的自定义CSS里给my-class加上height:auto:
.my-class { max-width: 50%; height: auto !important; /* 强制覆盖可能存在的内联样式 */ }
这样操作后,WordPress就不会再生成那些冗余的类和固定尺寸属性了,你的图片也能跟着窗口大小自动保持比例缩放啦!
内容的提问来源于stack exchange,提问作者Vineet Sharma
相关产品推荐
相关产品推荐

