have_rows()


WordPressのhave_rows()関数は、カスタムフィールドグループ内の繰り返しフィールド(リピーター)にデータが存在するかを確認するために使用されます。この関数は主にAdvanced Custom Fields(ACF)プラグインで利用されます。

構文

have_rows( string $field_name, mixed $post_id = false );

引数の説明

  • $field_name (string) — リピーターフィールドの名前。
  • $post_id (mixed) — データを取得する投稿ID。デフォルトは現在の投稿。

例1: リピーターフィールドの内容をループで表示

リピーターフィールドのデータを確認し、繰り返し内容を表示します。

<?php if ( have_rows('repeater_field') ) : while ( have_rows('repeater_field') ) : the_row(); ?>
<p><?php the_sub_field('sub_field_name'); ?></p>
<?php endwhile; endif; ?>

例2: 投稿のリピーターフィールドを取得

特定の投稿IDを指定してリピーターフィールドの内容を表示します。

<?php if ( have_rows('repeater_field', get_the_ID()) ) : while ( have_rows('repeater_field', get_the_ID()) ) : the_row(); ?>
<p><?php the_sub_field('sub_field_name'); ?></p>
<?php endwhile; endif; ?>

例3: ネストされたリピーターフィールドを表示

リピーターフィールド内に別のリピーターフィールドがある場合のループ処理です。

<?php if ( have_rows('parent_repeater') ) : while ( have_rows('parent_repeater') ) : the_row(); ?>
<h4><?php the_sub_field('parent_field_name'); ?></h4>
<?php if ( have_rows('child_repeater') ) : while ( have_rows('child_repeater') ) : the_row(); ?>
<p><?php the_sub_field('child_field_name'); ?></p>
<?php endwhile; endif; ?>
<?php endwhile; endif; ?>

例4: 条件付きでリピーターフィールドを表示

特定の条件に基づいてリピーターフィールドの内容を表示します。

<?php if ( have_rows('repeater_field') && is_singular('post') ) : while ( have_rows('repeater_field') ) : the_row(); ?>
<p><?php the_sub_field('sub_field_name'); ?></p>
<?php endwhile; endif; ?>

例5: 最初のリピーターフィールドのみを表示

ループを途中で停止して、最初のフィールド内容のみを表示します。

<?php if ( have_rows('repeater_field') ) : the_row(); ?>
<p><?php the_sub_field('sub_field_name'); ?></p>
<?php endif; ?>

注意事項

  • have_rows()関数は、Advanced Custom Fieldsプラグインがインストールされている場合に使用可能です。
  • リピーターフィールドの名前は、ACFで設定した正確な名前を使用してください。
  • リピーターフィールドの使用には投稿タイプやテンプレートの適切な設定が必要です。