Search code examples
javascriptwordpressadvanced-custom-fields

Remove all rows from an Advanced Custom Field Repeater (frontend, Javascript)


We have a repeater field on our WordPress website that can display hundreds of rows of data, these can all be imported in via copy and paste, that auto generates the rows. If we want to re-import this data, we would have to remove the existing rows first beforehand. There may also be scenarios we want to remove all data to start from scratch. However, ACF doesn't provide the option to remove all rows from a repeater in one simple frontend action. There is the option to remove each one one by one, however this is time consuming. The PHP method isn't also viable, as it doesn't provide immediate feedback from a UI perspective.

I've visited ACF's JavaScript API page and scrolled down to "remove field.remove()". This states that it "removes the field from the DOM and unregisters all assigned events, actions and filters". I have attempted to test this by adding a simple global JavaScript function that loops through the repeater field rows, and then remove them one by one:

function removeAllRepeaterFields() {
    jQuery(".acf-repeater > .acf-table > tbody > tr.acf-row:not(.acf-clone)").each(function( index, element ) {
        var id = element.dataset.id;
        var field = acf.getField('field_' + id);
        if ( field ) {
            field.remove();
        }
    });
}

However when I try this in the browser's console, nothing happens. Any assistance on this will be greatly appreciated! :-)


Solution

  • After a bit more tweaking, I've discovered that you don't need to use ACF's JS API to remove them, you simply just need to remove the entire element; once you click the Save/Update button, the removed fields are taken into consideration, and updated accordingly. Therefore the function in the question becomes the following:

    function removeAllRepeaterFields() {
        jQuery(".acf-repeater > .acf-table > tbody > tr.acf-row:not(.acf-clone)").each(function( index, element ) {
            element.remove();
        });
    }
    

    The documentation requires updating to mention this.