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

如何按现有逻辑获取并输出图片alt属性?

解决WordPress主题中获取并输出图片alt属性的问题

1. 修改PHP后端代码,获取图片alt属性

在现有获取图片属性的逻辑中,添加获取alt文本的代码,并将其存入图片属性数组:

// Get images attributes
$images = array();
foreach ( $galleries as $meta_key => $gallery ) {
    $attachment_ids = array_filter( explode( ',', $gallery ) );
    foreach ( $attachment_ids as $key => $attachment_id ) {
        $full_size_image             = wp_get_attachment_image_src( $attachment_id, 'full' );
        $single                      = wp_get_attachment_image_src( $attachment_id, 'shop_single' );
        $thumbnail                   = wp_get_attachment_image_src( $attachment_id, 'shop_thumbnail' );
        $catalog                     = wp_get_attachment_image_src( $attachment_id, 'shop_catalog' );
        // 获取图片的alt属性
        $image_alt                   = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
        $images[ $meta_key ][ $key ] = array(
            'single'                  => $single[0],
            'single_w'                => $single[1],
            'single_h'                => $single[2],
            'thumbnail'               => $thumbnail[0],
            'catalog'                 => $catalog[0],
            'data-src'                => $full_size_image[0],
            'data-large_image'        => $full_size_image[0],
            'data-large_image_width'  => $full_size_image[1],
            'data-large_image_height' => $full_size_image[2],
            'alt'                     => $image_alt // 将alt属性加入数组
        );
    }
}

2. 修改前端JS代码,正确输出alt属性

你之前的错误是把变量直接写在字符串引号内,导致输出固定文本。现在按照和其他属性一致的方式,拼接后端传递的image['alt']变量:

output_thumb += '<div>';
output_thumb += '<img  alt="' + image['alt'] + '" width="' + image['single_w'] + '" height="' + image['single_h'] + '" src="' + img_single + '" class="attachment-shop_single size-shop_single" data-src="' + image['data-src'] + '" data-large_image="' + image['data-large_image'] + '" data-large_image_width="' + image['data-large_image_width'] + '" data-large_image_height="' + image['data-large_image_height'] + '"/>';
output_thumb += '</div>';

关键说明

  • 后端通过get_post_meta函数读取WordPress附件的alt文本,该值存储在_wp_attachment_image_alt元字段中
  • 前端拼接HTML字符串时,必须将变量放在引号外部,用+连接,才能解析变量的实际值,而非输出变量名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:48:11