Created
September 12, 2024 03:43
-
-
Save elliott-w/d65ba9e1d8fbcdccc276357041348558 to your computer and use it in GitHub Desktop.
Collapse acf repeater rows by default
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add the "Collapse by default" checkbox to the repeater field settings | |
add_action('acf/render_field_settings', 'add_collapse_setting_to_repeater_field', 10, 1); | |
function add_collapse_setting_to_repeater_field($field) { | |
if ($field['type'] == 'repeater') { | |
acf_render_field_setting($field, array( | |
'label' => __('Collapse by default', 'text-domain'), | |
'instructions' => __('Collapse all rows by default when editing.', 'text-domain'), | |
'type' => 'true_false', | |
'name' => 'collapse_by_default', | |
'ui' => 1 | |
)); | |
} | |
} | |
// Add the data-collapse attribute to the repeater field when it is rendered | |
add_filter('acf/prepare_field', 'add_data_collapse_attribute_to_repeater_field'); | |
function add_data_collapse_attribute_to_repeater_field($field) { | |
if ($field['type'] === 'repeater') { | |
$field['wrapper']['data-collapse'] = isset($field['collapse_by_default']) ? $field['collapse_by_default'] : 0; | |
} | |
return $field; | |
} | |
add_action('acf/input/admin_footer', 'collapse_repeater_rows_on_page_load'); | |
function collapse_repeater_rows_on_page_load() { | |
?> | |
<script type="text/javascript"> | |
(function ($) { | |
acf.addAction('ready', function () { | |
$('[data-collapse="1"]').each(function () { | |
$(this).find('.acf-row').each(function () { | |
// If row is not collapsed and is not a clone used to create new rows | |
if (!$(this).hasClass('-collapsed') && !$(this).hasClass('acf-clone')) { | |
$(this).find('.acf-icon.-collapse').trigger('click'); | |
} | |
}); | |
}); | |
}); | |
})(jQuery); | |
</script> | |
<?php | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment