在 WordPress 里,媒体库上传图片时,系统会默认把「文件名」填到「标题」字段,而「替代文本(alt)」字段是空的。
要让前端输出的 < img alt=”…”> 直接调用「标题」字段,只需要把官方函数里缺省的 alt 参数改掉即可。下面给出 3 种最常见场景的写法,你直接复制到主题(或子主题)的对应文件里就能生效。
文章正文(the_content)里的图片
WordPress 自动生成的 < img> 标签会通过 wp-image-${id} 这个 class 把附件 ID 带出来,我们可以用 the_content 过滤器做一次性替换,不用改任何模板。
/* 让正文中的 <img alt=""> 自动调用图片“标题” */
add_filter( 'the_content', 'auto_alt_from_title', 999 );
function auto_alt_from_title( $content ) {
return preg_replace_callback(
'/<img[^>]+class="[^"]*wp-image-(\d+)[^"]*"[^>]*>/i',
function( $matches ) {
$img_tag = $matches[0];
$id = (int) $matches[1];
// 如果已经手动写了 alt,就跳过
if ( false !== strpos( $img_tag, 'alt=' ) && ! preg_match( '/alt=["\']\s*["\']/', $img_tag ) ) {
return $img_tag;
}
$title = get_the_title( $id ); // 拿到“标题”
$title = esc_attr( strip_tags( $title ) );
// 把 alt 插进去
return str_replace( '<img', '<img alt="' . $title . '"', $img_tag );
},
$content
);
}
特色图片(缩略图)
在任意模板文件(single.php、archive.php、page.php 等)里把原来的 the_post_thumbnail() 改成下面这样即可:
// 先拿到图片“标题”
$thumb_id = get_post_thumbnail_id();
$alt_text = get_the_title( $thumb_id ); // 这里读的就是“标题”字段
// 再输出,alt 参数强制写进去
the_post_thumbnail( 'full', [ 'alt' => esc_attr( $alt_text ) ] );
如果你希望全局生效,不想每次都写模板,可以在 functions.php 里一次性过滤:
/* 特色图片默认 alt 调用“标题” */
add_filter( 'wp_get_attachment_image_attributes', 'force_alt_to_title', 10, 2 );
function force_alt_to_title( $attr, $attachment ) {
// 如果主题/插件已经手动给了 alt,就尊重它
if ( empty( $attr['alt'] ) ) {
$attr['alt'] = esc_attr( get_the_title( $attachment->ID ) );
}
return $attr;
}
自己用 wp_get_attachment_image() 调用的图
只要写一行即可:
echo wp_get_attachment_image(
$image_id,
'large',
false,
[ 'alt' => get_the_title( $image_id ) ] // 直接读“标题”
);
WordPress 默认 alt 字段为空;「标题」字段等于上传时的文件名(可手动改)。
用 get_the_title( $attachment_id ) 就能拿到「标题」。
不想改模板就用过滤器:the_content 针对正文,wp_get_attachment_image_attributes 针对所有 wp_get_attachment_image() / 特色图片。
把上面代码丢进子主题 functions.php,以后上传图片时哪怕不填「替代文本」,前台也会自动把「标题」作为 alt 输出,SEO 和无障碍一次性解决。