WordPress 6.3:如何在普通页面显示媒体库图片描述?
解决WordPress普通页面侧边显示图片描述的问题
问题分析
你原代码仅针对文章的特色图像生效,且缺少容错处理——如果页面未设置特色图像,会触发PHP警告导致钩子失效;另外若侧边栏的图片并非页面特色图像,post_thumbnail_html钩子根本不会被触发。
方案1:针对页面特色图像的修正代码
如果侧边栏的图片是当前页面的特色图像,用以下代码替代原代码,增加容错与安全处理:
add_action( 'post_thumbnail_html', 'custom_description', 10 ); function custom_description( $html ) { // 获取当前页面/文章的特色图像ID $thumbnail_id = get_post_thumbnail_id(); // 先检查是否存在特色图像,避免报错 if ( $thumbnail_id ) { $attachment = get_post( $thumbnail_id ); // 获取媒体库中设置的图片描述 $beschriftung = $attachment->post_excerpt; if ( !empty( $beschriftung ) ) { // 用esc_html过滤内容,防止XSS风险 $html .= '<p class="em_bild">' . esc_html( $beschriftung ) . '</p>'; } } return $html; }
方案2:针对所有插入页面的图片(含侧边栏)
如果侧边栏的图片是直接插入的(非特色图像),使用wp_get_attachment_image过滤器,对所有通过WordPress内置函数输出的图片添加描述:
add_filter( 'wp_get_attachment_image', 'add_image_description_to_attached_images', 10, 3 ); function add_image_description_to_attached_images( $html, $attachment_id, $size ) { $attachment = get_post( $attachment_id ); $beschriftung = $attachment->post_excerpt; if ( !empty( $beschriftung ) ) { $html .= '<p class="em_bild">' . esc_html( $beschriftung ) . '</p>'; } return $html; }
方案3:手动调用特定图片的描述
如果侧边栏是自定义模板或短代码调用指定图片,可直接通过图片ID获取描述:
// 替换123为你的图片ID $attachment_id = 123; $attachment = get_post( $attachment_id ); if ( $attachment && !empty( $attachment->post_excerpt ) ) { echo '<p class="em_bild">' . esc_html( $attachment->post_excerpt ) . '</p>'; }
内容的提问来源于stack exchange,提问作者Conny
相关产品推荐
相关产品推荐

