Home › Forums › General Issues › Select Field + Add your own option? › Reply To: Select Field + Add your own option?
I have done it. So if you want to create Select values on the fly you can use this code. This code saves the “value : Label” though which is what I need. It sanitises the value you enter to slugify it, so its saved as “my-customer : My Customer” in ACFs field choices. If the value is to be the label its easily adapted.
You need to create a new text field for the “New” value you want to add. Then grab the old and new acf field_ids to use in the code.
function amity_pre_save_post( $post_id )
{
// Assign the field IDs to variables
$select_field_id = 'field_6346f63fec6c2';
$select_new_field_id = 'field_634ac0abf3d60';
// IF the new field value post cintains a value, then proceed
if(isset($_POST['acf'][$select_new_field_id]) && $_POST['acf'][$select_new_field_id] != '')
{
// Assign the new value to label and value
$label = $_POST['acf'][$select_new_field_id];
$value = sanitize_title($label);
// Get the ACF field settings
$field = get_field_object($select_field_id);
// Add the new fields value and label to the field settings
$field['choices'][$value] = $label;
// Update ACF field settings - adds new value into Select fields Choices in DB
acf_update_field($field);
// Asssign the Select field value to the new field value
$_POST['acf'][$select_field_id] = $value;
// Clear the new field value as we want it blank every time
$_POST['acf'][$select_new_field_id] = '';
}
}
add_filter('acf/save_post' , 'amity_pre_save_post', 1, 1 );
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.