acfで画像フィールドが複数あり、返り値がidの場合の出力
room_img1~room_img6まで画像フィールドがある場合
※画像サイズは複数(largeとthumbnail)に対応
<?php
$size_large = 'large';
$size_thumb = 'thumbnail';
$images = [];
for ($i = 1; $i <= 6; $i++) {
$field = 'room_img' . $i;
$attachment_id = get_field($field);
if ($attachment_id) {
$image_large = wp_get_attachment_image_src($attachment_id, $size_large);
$image_thumb = wp_get_attachment_image_src($attachment_id, $size_thumb);
$attachment = get_post($attachment_id);
$alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
$caption = get_the_excerpt($attachment);
// 念のため画像URLが取得できているかも確認
if ($image_large && $image_thumb) {
$images[] = [
'large' => $image_large[0],
'thumb' => $image_thumb[0],
'alt' => esc_attr($alt),
'caption' => esc_html($caption)
];
}
}
}
?>
テンプレートの出力部はswiperでスライドさせる場合
<div class="swiper-wrapper">
<?php foreach ($images as $img): ?>
<div class="swiper-slide">
<img src="<?php echo $img['src']; ?/>" alt="<?php echo $img['alt']; ?>" title="<?php echo $img['caption']; ?>">
<?php if ($img['caption']): ?>
<span><?php echo $img['caption']; ?></span>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div><!--/.swiper-wrapper-->