Skip to content

Instantly share code, notes, and snippets.

@mvaneijgen
Last active April 16, 2021 13:03
Show Gist options
  • Save mvaneijgen/41fbf1088c5fbc3b948c481cdea93dd8 to your computer and use it in GitHub Desktop.
Save mvaneijgen/41fbf1088c5fbc3b948c481cdea93dd8 to your computer and use it in GitHub Desktop.
Add toggle button to ACF flexible fields
function acf_toggle_flex()
{
?>
<script type="text/javascript">
(function($) {
acf.add_action('load', function($el) {
let $field = $el.find('.acf-field-flexible-content'); // Get flexabile fields
$field = Array.prototype.slice.call($field); // Convert to array
$field.forEach(function(container) { // Loop through all fields on the page
// Create button
let btn = document.createElement("a");
btn.classList.add('button', 'button-primary', 'toggle-flex-fields');
btn.innerText = 'Toggle';
// Prepend button on top of the container
container.prepend(btn);
// Get toggleable fields
const item = container.querySelectorAll(".layout");
// Add click event to button
btn.addEventListener('click', function(event) {
event.preventDefault();
item.forEach(function(item) {
item.classList.toggle('-collapsed')
});
});
});
});
})(jQuery);
</script>
<?php
}
add_action('acf/input/admin_footer', 'acf_toggle_flex');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment