• Advanced Custom Fields の Repeater Field の質問です。
    繰り返しフィールドに登録した画像をランダムで3件だけ表示させたいと思い、、
    Advanced Custom Fields のサイトを見て、以下のようなコードを書いたところ、
    「登録した個数分の重複ありのランダム表示」になっております。

    <?php while ( have_rows('作品') ) : the_row(); ?>
    
    <?php
    $rows = get_field('作品');
    $row_count = count($rows);
    $i = rand(0, $row_count - 1);
    $attachment_id = $rows[ $i ]['写真'];
    $size = 'full';
    $image = wp_get_attachment_image_src( $attachment_id, $size );
    ?>
    
    <?php echo '<img src="'.$image[0].'">'; ?>
    
    <?php endwhile; ?>

    ランダム(重複なし)に3件だけ表示をするには
    どのようにするとよいのでしょうか?

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • <?php while ( have_rows('作品') ) : the_row(); ?>
    <?php endwhile; ?>

    ↑で'作品'フィールドのループが成立している中でそれとは関係なしに

    $rows = get_field('作品');

    と、あらたに'作品'フィールドの配列を$rowsに格納してそちらからランダムに値を取り出しています。
    その処理が while ( have_rows('作品') )ループにより'作品'フィールドの個数分繰り返されているので重複しているんだと思います。

    <?php
    $photos = array();
    while ( have_rows( '作品' ) ) : the_row();
    	$photos[] = get_sub_field( '写真' );
    endwhile;
    
    if ( $photos ) {
    	$num = count( $photos ) > 2 ? 3 : count( $photos );
    	$results = array_rand( $photos, $num );
    	foreach ( $results as $result ) {
    		$image = wp_get_attachment_image_src( $result, 'full' );
    		echo '<img src="' . $image[0] . '">';
    	}
    }
    ?>

    または

    <?php
    $rows = get_field( '作品' );
    if ( $rows ) {
    	$num = count( $rows ) > 2 ? 3 : count( $rows );
    	$results = array_rand( $rows, $num );
    	foreach ( $results as $result ) {
    		$attachiment_id = $result['写真'];
    		$image = wp_get_attachment_image_src( $attachiment_id, 'full' );
    		echo '<img src="' . $image[0] . '">';
    	}
    }
    ?>

    共に作品に写真が含まれていない場合を考慮していません。

2件の返信を表示中 - 1 - 2件目 (全2件中)

トピック「Advanced Custom Fields の Repeater Field で、3件ランダム表示」には新たに返信することはできません。