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

如何在WordPress文章标题前显示特色图且不干扰后台列表展示

问题原因

the_title过滤器会在前后台所有调用文章标题的位置全局生效,WordPress后台的文章列表会对标题内容做HTML转义输出,所以你插入的img标签不会被渲染为图片,而是直接显示源代码。

修复后的代码

function featured_image_before_title($title, $id) { 
    // 后台访问、非文章类型、不在主循环内时,直接返回原标题
    if (is_admin() || get_post_type($id) !== 'post' || !in_the_loop()) {
        return $title;
    }
    $featuredimage = get_the_post_thumbnail($id, 'thumbnail'); // 可自行修改第二个参数指定缩略图尺寸
    $title = $featuredimage . $title;
    return $title;
}

add_filter( 'the_title', 'featured_image_before_title', 10, 2 );

代码说明

  • 新增is_admin()判断:后台访问时直接跳过逻辑,避免影响后台标题展示
  • 新增in_the_loop()判断:仅修改WordPress主循环内的文章标题,避免侧边栏、相关推荐等非主循环位置的标题被意外加上特色图
  • 给get_the_post_thumbnail传入了文章ID参数,避免上下文异常时拿错缩略图,第二个参数可以自行指定需要的缩略图尺寸,比如post-thumbnail、medium等

修改后前端主循环的文章标题前仍会正常渲染特色图,后台文章列表的标题会恢复为纯文本展示,不会出现HTML源代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:27:04