Skip to content

Instantly share code, notes, and snippets.

@laxmariappan
Created November 12, 2024 18:18
Show Gist options
  • Save laxmariappan/80942e6acb5bfab6631e17e243fa8554 to your computer and use it in GitHub Desktop.
Save laxmariappan/80942e6acb5bfab6631e17e243fa8554 to your computer and use it in GitHub Desktop.
Get all ACF fields and their sub fields for a given page id
<?php
function get_all_acf_fields_and_subfields($page_id) {
$all_fields = [];
// Get all field groups associated with the page
$field_groups = acf_get_field_groups(['post_id' => $page_id]);
if ($field_groups) {
foreach ($field_groups as $field_group) {
$fields = acf_get_fields($field_group['key']);
if ($fields) {
foreach ($fields as $field) {
$field_data = [
'name' => $field['name'],
'label' => $field['label'],
'key' => $field['key'],
'type' => $field['type'],
'value' => get_field($field['name'], $page_id),
];
// Handle sub fields (repeaters, flexible content, etc.)
if (in_array($field['type'], ['repeater', 'flexible_content', 'group'])) {
$field_data['sub_fields'] = get_sub_fields_recursive( $field, $page_id);
}
$all_fields[] = $field_data;
}
}
}
}
return $all_fields;
}
function get_sub_fields_recursive($field, $page_id) {
$sub_fields_data = [];
if (have_rows($field['name'], $page_id)) {
while(have_rows($field['name'], $page_id)) {
the_row();
foreach ($field['sub_fields'] as $sub_field) {
$sub_field_data = [
'name' => $sub_field['name'],
'label' => $sub_field['label'],
'key' => $sub_field['key'],
'type' => $sub_field['type'],
'value' => get_sub_field($sub_field['name']), // No $page_id here, inside the loop.
];
if (in_array($sub_field['type'], ['repeater', 'flexible_content', 'group'])) {
$sub_field_data['sub_fields'] = get_sub_fields_recursive($sub_field, $page_id); //recursive call
}
$sub_fields_data[] = $sub_field_data;
}
}
}
return $sub_fields_data;
}
// Example usage:
$acf_fields = get_all_acf_fields_and_subfields($page_id);
// Now you can loop through $acf_fields and access all fields and subfields.
echo '<pre>'; print_r($acf_fields); echo '</pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment