WordPressのACF(Advanced Custom Fields)を使用すると、カスタムフィールドで繰り返しフィールド(リピートフィールド)を作成できます。この記事では、繰り返しフィールドの中にさらに繰り返しフィールドを入れ、データを制御・表示する方法について解説します。
繰り返しフィールドの中に繰り返しフィールを入れる
親フィールド名:○○○
子フィールド名:△△△
以下のコードを使用して、親フィールドのループ内で子フィールドを表示します。
<?php if (have_rows('○○○')): ?>
<?php while (have_rows('○○○')): the_row(); ?>
<!-- 親フィールド○○○の中身をここに記述 -->
<div class="parent-item">
<h2><?php the_sub_field('親フィールド内のタイトル'); ?></h2>
<!-- 子フィールド△△△のループ -->
<?php if (have_rows('△△△')): ?>
<ul class="child-list">
<?php while (have_rows('△△△')): the_row(); ?>
<li>
<p><?php the_sub_field('子フィールド内のテキスト'); ?></p>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
</div>
<?php endwhile; ?>
<?php endif; ?>
コードの説明
親フィールド(○○○)のループ
have_rows('○○○')
で親フィールドの繰り返しをチェック。
while (have_rows('○○○')): the_row();
でループを開始し、親フィールド内のデータを処理。
子フィールド(△△△)のループ
親フィールドのループ内で have_rows('△△△')
をチェック。
while (have_rows('△△△')): the_row();
で子フィールド内のデータを処理。
the_sub_field()
を使用
親や子フィールドの各データを取得して表示します。
HTML構造
親フィールドの内容を <div>
で囲み、その中に子フィールドを <ul>
と <li>
でリスト表示。
出力結果
<div class="parent-item">
<h2>親アイテム1</h2>
<ul class="child-list">
<li><p>子アイテムA</p></li>
<li><p>子アイテムB</p></li>
</ul>
</div>
<div class="parent-item">
<h2>親アイテム2</h2>
<ul class="child-list">
<li><p>子アイテムC</p></li>
<li><p>子アイテムD</p></li>
</ul>
</div>
応用例:段落番号やカスタムスタイルの追加
段落番号の追加
段落番号を追加したい場合、PHPのカウンター変数を使用します。
<?php if (have_rows('○○○')): $parent_count = 0; ?>
<?php while (have_rows('○○○')): the_row(); $parent_count++; ?>
<div class="parent-item">
<h2><?php echo $parent_count . '. '; ?><?php the_sub_field('親フィールド内のタイトル'); ?></h2>
<?php if (have_rows('△△△')): $child_count = 0; ?>
<ul class="child-list">
<?php while (have_rows('△△△')): the_row(); $child_count++; ?>
<li><?php echo $child_count . '. '; ?><?php the_sub_field('子フィールド内のテキスト'); ?></li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
</div>
<?php endwhile; ?>
<?php endif; ?>
出力結果
<div class="parent-item">
<h2>1. 親アイテム1</h2>
<ul class="child-list">
<li>1. 子アイテムA</li>
<li>2. 子アイテムB</li>
</ul>
</div>
<div class="parent-item">
<h2>2. 親アイテム2</h2>
<ul class="child-list">
<li>1. 子アイテムC</li>
<li>2. 子アイテムD</li>
</ul>
</div>
注意点
フィールドの存在確認
have_rows()
を使ってフィールドの存在を必ず確認し、エラーを防ぎます。
フィールドの構造
ACFの管理画面で、親フィールドと子フィールドの階層構造が正しく設定されていることを確認します。
スタイルの調整
必要に応じてCSSを使い、親フィールドと子フィールドのデザインを調整します。
大阪のホームページ制作会社TREVOでは、ホームページ制作に関する情報を掲載しています。最短2日で仮サイトを公開するサービスやSEO対策に特化したホームページ制作、オリジナルホームページデザイン、ライティング、リスティング広告、WEBマーケティングなどのサービスをご紹介しています。