みなさん、こんにちは!
ACF(Advanced Custom Fields)の繰り返しを使用してフロント側でデザインを作成するときに
1つ目だけHTMLソースを変えたいってことありませんか?
今回はその備忘録を載せておきたいと思います。
ACF側の設定項目
・フィールド名 :loop_test
・フィールドタイプ:繰り返しフィールド
◆サブフィールド
1)フィールド名 :loop_test_img
フィールドタイプ :画像
返り値のフォーマット:画像配列
2)フィールド名 :loop_test_text
フィールドタイプ:テキスト
ソース
【繰り返しフィールドの1つめのみ取得】
<?php if (have_posts()): ?>
<?php while (have_posts()) : the_post(); ?>
<section id="indexInfo">
<div class="inner flexbox fw">
<!-- 1つ目のみ取得 -->
<?php
$acf_rows = get_field('loop_test');
$first_row = $acf_rows[0]; //1つめ
$img = $first_row['loop_test_img' ];
$url = $img['sizes']['medium'];
$alt = $img['alt'];
$text = $first_row['loop_test_text'];
?>
<div>
<picture>
<source srcset="" media="(min-width: 800px)">
<img src="<?php echo $url ?>" alt="<?php echo $text ?>">
</picture>
<p><?php echo $text ?></p>
</div>
<!-- 1つ目のみ取得 -->
</div>
</section>
<?php endwhile; ?>
<?php endif; ?>
【繰り返しフィールドの2つ目以降を取得】
<div>
<ul>
<?php if( have_rows( 'loop_test' ) ): ?> //ACF通常の書き方
<?php while( have_rows( 'loop_test' ) ): the_row(); $counter++; ?> //ACF通常の書き方にカウンターを設置
<?php
$img = get_sub_field( 'loop_test_img' );
$url = $img['sizes']['medium'];
$alt = $img['alt'];
$text = get_sub_field( 'loop_test_text' );
?>
<?php if ($counter >= 2) : ?> //2つ目から取得する
<li>
<picture>
<source srcset="" media="(min-width: 800px)">
<img src="<?php echo $url ?>" alt="<?php echo $text ?>">
</picture>
<p><?php echo $text ?></p>
</li>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
</ul>
</div>
この2つをつなげると…
<?php if (have_posts()): ?>
<?php while (have_posts()) : the_post(); ?>
<section id="indexInfo">
<div class="inner flexbox fw">
<!-- 1つ目のみ取得 -->
<?php
$acf_rows = get_field('loop_test');
$first_row = $acf_rows[0]; //1つめ
$img = $first_row['loop_test_img' ];
$url = $img['sizes']['medium'];
$alt = $img['alt'];
$text = $first_row['loop_test_text'];
?>
<div>
<picture>
<source srcset="" media="(min-width: 800px)">
<img src="<?php echo $url ?>" alt="<?php echo $text ?>">
</picture>
<p><?php echo $text ?></p>
</div>
<!-- 1つ目のみ取得 -->
<!-- 1つ目を省いて2つ目以降から取得 -->
<div>
<ul>
<?php if( have_rows( 'loop_test' ) ): ?> //ACF通常の書き方
<?php while( have_rows( 'loop_test' ) ): the_row(); $counter++; ?> //ACF通常の書き方にカウンターを設置
<?php
$img = get_sub_field( 'loop_test_img' );
$url = $img['sizes']['medium'];
$alt = $img['alt'];
$text = get_sub_field( 'loop_test_text' );
?>
<?php if ($counter >= 2) : ?> //2つ目から取得する
<li>
<picture>
<source srcset="" media="(min-width: 800px)">
<img src="<?php echo $url ?>" alt="<?php echo $text ?>">
</picture>
<p><?php echo $text ?></p>
</li>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
</ul>
</div>
<!-- 1つ目を省いて2つ目以降から取得 -->
</div>
</section>
<?php endwhile; ?>
<?php endif; ?>
みなさんも試してみてくださいね!