reset_rows()


WordPress関数reset_rows()は、カスタムフィールドやACF(Advanced Custom Fields)で使用されるループ内の行インデックスをリセットするために使用されます。

構文

reset_rows();

例 1: ACFの行インデックスをリセット

カスタムフィールド「repeater_field」を複数回ループする場合に行インデックスをリセットします。

<?php
if ( have_rows('repeater_field') ) {
    while ( have_rows('repeater_field') ) {
        the_row();
        // 繰り返し処理
    }
    reset_rows();
    while ( have_rows('repeater_field') ) {
        the_row();
        // もう一度繰り返し処理
    }
}
?>

例 2: 条件によるリセットの使用

条件に基づいてインデックスをリセットする場合。

<?php
if ( have_rows('repeater_field') ) {
    while ( have_rows('repeater_field') ) {
        the_row();
        if ( get_sub_field('condition') === 'value' ) {
            reset_rows();
            break;
        }
    }
}
?>

例 3: 入れ子ループ内でのリセット

ネストされたループでリセットを使用する例。

<?php
if ( have_rows('parent_field') ) {
    while ( have_rows('parent_field') ) {
        the_row();
        if ( have_rows('child_field') ) {
            while ( have_rows('child_field') ) {
                the_row();
                // 子フィールド処理
            }
            reset_rows();
        }
    }
}
?>

例 4: ACFブロックテンプレートでの使用

ACFブロックのテンプレートで行をリセットする例。

<?php
if ( have_rows('block_field') ) {
    while ( have_rows('block_field') ) {
        the_row();
        // ブロック内処理
    }
    reset_rows();
}
?>

例 5: カウントのリセット

行のカウントをリセットする場合に使用する例。

<?php
$count = 0;
if ( have_rows('repeater_field') ) {
    while ( have_rows('repeater_field') ) {
        the_row();
        $count++;
    }
    reset_rows();
    echo "リセット後のカウント: $count";
}
?>

注意点

  • reset_rows()は、have_rows()the_row()を使用したACFリピーターフィールド内でのみ動作します。
  • リセットを適切な場所で行わないと、意図しない結果を引き起こす可能性があります。