acf_add_loop()


関数acf_add_loop()は、WordPressのAdvanced Custom Fieldsプラグインを使用して、複数のリピート可能なフィールドをループ処理するために使用されます。この関数を使用することで、リピート可能なデータを効率的に取得および表示することができます。

シンタックス

acf_add_loop( array $args );
  • $args (array) — ループ処理に必要な設定を含む配列。

例1: 基本的なリピートフィールドのループ

リピート可能なフィールドのすべての項目を表示します。

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

例2: 条件付きループ処理

特定のサブフィールドの値が一致する場合のみデータを表示します。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        if ( get_sub_field( 'sub_field_name' ) === '特定の値' ) {
            echo get_sub_field( 'another_sub_field_name' );
        }
    }
}
?>

例3: ループ内で画像を取得

リピートフィールド内の画像を表示します。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        $image = get_sub_field( 'image_field_name' );
        echo '<img src="' . $image['url'] . '" alt="' . $image['alt'] . '">';
    }
}
?>

例4: 複数のサブフィールドを結合して表示

複数のサブフィールドの値を結合して1つの文字列として表示します。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        echo get_sub_field( 'field_1' ) . ' - ' . get_sub_field( 'field_2' );
    }
}
?>

例5: サブフィールドのカスタムHTMLラップ

サブフィールドの値をHTMLタグでラップして表示します。

<?php
if ( have_rows( 'repeater_field_name' ) ) {
    while ( have_rows( 'repeater_field_name' ) ) {
        the_row();
        echo '<div class="custom-class">' . get_sub_field( 'sub_field_name' ) . '</div>';
    }
}
?>

注意事項

  • この関数を使用する際は、リピート可能なフィールドが正しく設定されていることを確認してください。
  • the_row()を使用することで、ループ内の現在の行にアクセスできます。
  • サブフィールド名が正しいことを再確認してください。