I'm importing some data, and generating posts with ACF information, which works well for text fields, and choice fields where the option already exists - but I'd like to add new options to choice fields as required.
I'd hope this is something easy to do, but starting to suspect it's either difficult, or I'm barking up the wrong tree.
To put it another way, when looking at a choice field in the admin panel, we can type in a list of choices - I want to be able to add a choice to this list programatically
Enter each choice on a new line. For more control, you may specify both a value and label like this: red : Red
Choices
[Input text box here]
Enter each choice on a new line. For more control, you may specify both a value and label like this: red : Red
This is completely possible with ACF. You can update field values by importing the field group again inside your code. You will need to loop trough your fieldgroup fields, while looping trough the fields you will append your option to the right field key.
What you will need is:
You need to know your field group key for example: group_6800b73ce24b4
You need to know your field key you want to update, for example: field_6800baab64d89
Let's say i want to add the value "Cola" to my existing field (field_6800baab64d89) that is inside my group (group_6800b73ce24b4). I will need to run this script:
// Load the full field group by key or ID
$field_group = acf_get_field_group('group_6800b73ce24b4');
if (!$field_group) return;
// Load all fields associated with this field group
$fields = acf_get_fields($field_group['key']);
// Modify the field you care about
foreach ($fields as &$field) {
if ($field['key'] === 'field_6800baab64d89') {
if (!isset($field['choices']['cola'])) {
$field['choices']['cola'] = 'Cola';
}
}
}
// Assign updated fields back to the field group
$field_group['fields'] = $fields;
// Import the full modified field group
acf_import_field_group($field_group);
This will add the option "Cola" to the selector/radio/checkbox field (field_6800baab64d89).
Don't forget to change the group and field key. Good luck :)