ACFのリピートフィールドの画像1枚目だけを取得して表示する方法(archiveなど)
advanced customfieldのrepeat fieldで複数の画像を登録させているときに、
アーカイブ(一覧ページ)に表示させるときに、何枚も表示させるとおかしいので、
リピートフィールドの画像の1枚目だけを取得して、表示させる方法です。
<?php //リピートフィールドに入っている1枚目の画像だけを表示させる記述
$rows = get_field('mainphoto' ); // すべてのrow(内容・行)をいったん取得する
$first_row = $rows[0]; // 1行目だけを$first_rowに格納しますよ~
$first_row_image = $first_row['mainphotoin' ]; // get the sub field value 
$image = wp_get_attachment_image_src( $first_row_image, 'full' );
?>
<img src="<?php echo $image[0]; ?>" />
※mainphotoの部分を自分で作ったカスタムフィールド名に変更してください。
※mainphotoinの部分を、リピートフィールド内のカスタムフィールド名にしてください。
参考ページ:https://lib.ridesign.jp/lib_wp/acf-repeater/
追記:リピートフィールドに入っている2枚目以降の画像を表示させる記述
<!-- リピートフィールドに入っている2枚目以降の画像を表示させる記述 -->
<ul>
<?php if( have_rows( 'sekoumaephoto' ) ): ?> 
<?php while( have_rows( 'sekoumaephoto' ) ): the_row(); $counter++; ?>
<?php $img = get_sub_field( 'sekoumaephotoin' ); ?>
 
<?php if ($counter >= 2) : ?> 
<li>
<figure>
<a href="<?php echo wp_get_attachment_url( get_sub_field( 'sekoumaephotoin',$post->ID) ); ?>">
<?php
$thumbnail_id = get_post_thumbnail_id($post->ID); //アタッチメントIDの取得
$image = wp_get_attachment_image_src( get_sub_field('sekoumaephotoin'), 'full' ); 
echo '<img src="'.$image[0].'" width="'.$image[1].'" height="'.$image[2].'" />';
?>
</a>
</figure>
</li>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
</ul>
<!-- リピートフィールドに入っている2枚目以降の画像を表示させる記述 -->
※sekoumaephoto カスタムフィールド名
※sekoumaephotoin リピートフィールド名
※同じページ内に、2か所2番目以降のリピートフィールドを表示させる場合は、
$counterの部分を$counter02などに変更したものを2個目のものに付けてください。
$counterは変数なので同じものだとおかしくなります。
関連記事はこちら!
スポンサーリンク

 
 







