WordPress如何获取媒体库图片alt文本、标题、说明、描述等元数据
问题原因
你调用的_wp_attachment_description、_wp_attachment_caption两个元键不存在于WordPress默认的post_meta表中。
WordPress 附件(含图片)属于内置的attachment文章类型,只有Alt文本是单独存储在post_meta表的_wp_attachment_image_alt字段中,其余几个字段的存储位置如下:
- 图片标题:存储在wp_posts表的
post_title字段 - 图片说明(Caption):存储在wp_posts表的
post_excerpt字段 - 图片描述(Description):存储在wp_posts表的
post_content字段
正确调取代码
// 示例场景:文章循环内获取特色图片的所有字段 $image_id = get_post_thumbnail_id( get_the_ID() ); $attachment = get_post( $image_id ); // 各字段赋值 $image_alt_text = get_post_meta($image_id, '_wp_attachment_image_alt', true); $image_title = $attachment->post_title; $image_caption = $attachment->post_excerpt; $image_description = $attachment->post_content;
注意事项
输出字段到前端时建议做转义处理提升安全性:
- 输出到HTML标签属性(如img的alt、title属性)时使用
esc_attr()包裹 - 输出到页面正文内容时使用
esc_html()包裹
内容的提问来源于stack exchange,提问作者dvlpr.963
相关产品推荐
相关产品推荐

