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

Echo ACF媒体附件自定义字段image_size无法正常输出问题求助

问题原因

ACF 图库字段默认返回的是包含所有选中图片数据的二维数组,你直接访问$images['id']无法获取到有效图片ID,结合你后续输出第一张图库图片的逻辑,需要取第一张图片的ID来查询附件自定义字段。

修正代码(仅输出第一张图)

<?php 
$images = get_field('documentation', $post->ID);
if( $images ): 
    // 取第一张图片ID查询自定义字段
    $documentation_class = get_field('image_size', $images[0]['id']);
?>                   
<figure class="<?php echo esc_attr($documentation_class); ?>">
    <img src="<?php echo esc_url($images[0]["sizes"]["large"]); ?>" alt="<?php echo esc_attr($images[0]['alt']); ?>">
</figure>
<?php endif; ?>

遍历输出所有图库图片的写法

如果你需要输出所有选中的图库图片,新增一层foreach循环即可:

<?php 
$images = get_field('documentation', $post->ID);
if( $images ): 
    foreach( $images as $image ):
        $documentation_class = get_field('image_size', $image['id']);
?>                   
<figure class="<?php echo esc_attr($documentation_class); ?>">
    <img src="<?php echo esc_url($image["sizes"]["large"]); ?>" alt="<?php echo esc_attr($image['alt']); ?>">
</figure>
<?php 
    endforeach;
endif; 
?>

注:代码中新增的esc_attr、esc_url为WordPress推荐的安全转义函数,避免输出内容异常导致的前端问题。

内容的提问来源于stack exchange,提问作者R-G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:04