You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Feed内容移除首张图片仅显文本,需保留img属性且代码失效求助

解决Feed中保留img标签属性但不显示图片的问题

你的问题出在之前的代码是直接把整个<img>标签删掉了,这当然没法保留标签属性啦!咱们要做的是让图片不显示,但完整保留img标签和它的所有属性,下面给你两种可行的方案:

方案一:给img标签添加隐藏样式(推荐)

这种方式会给所有Feed里的img标签加上display:none的样式,图片不会渲染出来,但标签本身和所有属性都原封不动保留着:

function hide_images_in_feed($content) {
    if (is_feed()) {
        // 遍历所有img标签,添加或修改style属性实现隐藏
        $content = preg_replace_callback('/<img([^>]+)>/i', function($matches) {
            $img_attrs = $matches[1];
            // 检查是否已有style属性
            if (strpos($img_attrs, 'style=') !== false) {
                // 已有style,追加隐藏样式
                return preg_replace('/style="([^"]+)"/i', 'style="$1; display:none !important"', "<img{$img_attrs}>");
            } else {
                // 没有style,直接添加新的style属性
                return "<img{$img_attrs} style=\"display:none !important\">";
            }
        }, $content);
    }
    return $content;
}
add_filter('the_content_rss', 'hide_images_in_feed');
add_filter('the_content', 'hide_images_in_feed');

方案二:清空img标签的src属性

如果更倾向于让图片完全无法加载(而非隐藏),可以把所有img的src置为空,其他属性依然保留:

function remove_image_src_in_feed($content) {
    if (is_feed()) {
        // 替换所有img的src为空字符串,保留其他属性
        $content = preg_replace('/(<img[^>]+)src="[^"]+"([^>]*>)/i', '$1src=""$2', $content);
    }
    return $content;
}
add_filter('the_content_rss', 'remove_image_src_in_feed');
add_filter('the_content', 'remove_image_src_in_feed');

为什么之前的代码无效?

你之前的preg_replace("/<img[^>]+>/i", "", $content, 1)是直接把第一个匹配到的img标签整个替换成空字符串,相当于直接删掉了标签和所有属性,完全不符合你“保留属性”的需求,所以才没达到预期效果。

内容的提问来源于stack exchange,提问作者abukotsh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:21:01