the_row()


WordPress関数the_row()は、have_rows()関数と共に使用され、Advanced Custom Fields(ACF)プラグインでリピートフィールドの現在の行を取得するために使用されます。

構文

<?php the_row(); ?>

例 1: 現在の行の値を取得

以下のコードは、the_row()を使用して現在の行を処理します。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        // 行ごとの処理をここに記述
    }
}
?>

例 2: 行内のサブフィールドの値を表示

リピートフィールド内のサブフィールドの値を取得します。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        echo get_sub_field( 'sub_field_name' );
    }
}
?>

例 3: 行ごとの特定の条件に基づいて値を出力

条件によって出力を分ける例です。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        if ( get_sub_field( 'sub_field_name' ) === '特定の値' ) {
            echo 'この行は特定の条件を満たしています。';
        }
    }
}
?>

例 4: 行のインデックスを取得

現在の行のインデックスを取得します。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        echo '現在の行インデックス: ' . get_row_index();
    }
}
?>

例 5: サブフィールドに基づいたCSSクラスの追加

サブフィールドの値を元にCSSクラスを追加する例です。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        $class = get_sub_field( 'class_name' );
        echo '<div class="' . $class . '">行の内容</div>';
    }
}
?>

注意事項

  • the_row()は、必ずhave_rows()のループ内で使用してください。
  • リピートフィールドが空の場合、the_row()を呼び出すとエラーが発生する可能性があります。