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
相关产品推荐
相关产品推荐

