I love ACF, its great for developers and it seems to have so much support. BUT… Why is reset_rows() not in the documentation? I created a function that can delete repeater rows at different times in the code. I was using the rows loop each time expecting it to start at index 0 (or 1 in acf’s crazy way). But each loop started where the previous one left off.
This gave me grief for quite a while. I have only found ONE other topic with a small 3 word reply mentioning reset_rows(). ACF documentation has nothing that comes up when you searched reset_rows() or anything about reseting the row index. ITS NO WHERE!
So maybe this can save others from the grief. Here is how i use it successfully:
reset_rows('field_name', $post_id);
$post_id could be optional, havnt tried it..
Here is how i have placed it in my code
if( have_rows('related_trustees', $memberID) )
{
reset_rows('related_trustees', $memberID); // Start from begining (protects against previous loops)
echo 'Have rows';
$rowNum = 0; // ACF Rows start at index of 1
while( have_rows('related_trustees', $memberID) )
{
the_row();
$rowNum ++;
if(get_sub_field('trustee') == $userID)
{
$delrow = delete_row('related_trustees', $rowNum, $memberID);
break;
}
}
}
Let me know if theres a reason to this madness please.
1 Answer
It’s not in the documentation mainly because it’s an internal function, they weren’t expecting you to use or need it.
have_rows()
checks to see whether there is a currently active loop- if not, it creates a global with your repeater rows; if so, it picks up where you left off- then it lets you know whether there are rows remaining to be looped through. Your example is intriguing, seems to be a bit of a fringe scenario, but I can see how frustrating it would be. After jumping out of the loop midstream, you aren’t automatically returned to the beginning because the previous loop is still active and has rows remaining.
ACF doesn’t have a true rewind_posts()
equivalent, but you can either run the reset_rows()
function or the function it’s wrapping: acf_remove_loop()
(also internal and undocumented, sorry!). Whichever you use should probably be run right before your break
though, so you don’t end up with unexpected results from your if ( have_rows() )
should you ever be removing the last row and following it up with another loop.
An unrelated but interesting tidbit is that you actually don’t need the custom row counter, they provide get_row_index()
for just this purpose.