Home Forums Add-ons Repeater Field How do I programmatically delete all repeater rows?


How do I programmatically delete all repeater rows?

  • I have a repeater with a single field (image url), I want to delete them all so I can repopulate the repeater with new URLs, I’m currently using this:

    $images = get_field('images');
                    $index = 0;
                    foreach ($images as $image) {
                        delete_row('images', $index);

    But that will not delete the first row as it seems the row index is a normal count (not starting at zero)

    Is there a better way to do this?

  • Hi elliottc, maybe you could delete that meta field with delete_post_meta. You should pass the post ID.

    delete_post_meta($post_id, 'images');
  • Just change the counter to start at 1

    $index = 1;

    or do the loop in a different way

    $images = get_field('images');
    if (!empty($images)) {
      $count = count($images);
      for ($index=1; $index<=$count; $index++) {
        delete_row('images', $index);
  • Hi John, Thanks for your code.
    I had trouble with this today, not all rows were being removed.
    I needed to remove them in reverse order:

            $existing_locations = get_field('rp_locations', $post_id);
            if( !empty($existing_locations) )
                for( $index = count($existing_locations); $index > 0; $index-- )
                    delete_row('rp_locations', $index, $post_id);
  • Because delete_row returns a boolean based on if it succeeds or not I tend to clean the repeater field with a while loop by removing the first row until there is no rows left. Note the semicolon in the end of the line so we are just looping that while condition and not doing anything else. If needed, you can give post_id as a third parameter.

    while (delete_row('images', 1));

  • When using a loop method to delete the rows one at a time, always delete the last row each time, not the first.

    You won’t notice it on small repeaters, but on larger ones it can really bite.

    I used the delete first row method (as is commonly shown online, I think coz it’s easier) and for 376 rows in a repeater, it took 5244 seconds. Deleting the last row each time, it took 191 seconds.

    I do still want to find a faster way. But that was tonight’s optimisation

    Here’s what my code looks like:

    function deleteRows(string $acfRepeaterFieldKey, int $postID): void {
      $fieldValue = get_field($acfRepeaterFieldKey, $postID);
      if (is_array($fieldValue)){
        $remainingRows = count($fieldValue);
        while (have_rows($acfRepeaterFieldKey, $postID)) :
          delete_row($acfRepeaterFieldKey, $remainingRows--, $postID);
Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘How do I programmatically delete all repeater rows?’ is closed to new replies.