Last active
December 7, 2022 20:22
-
-
Save yaroslav-borodii/5630a0e049a7560a2d9704abcf31cf3b to your computer and use it in GitHub Desktop.
Save custom select options
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 | |
/** | |
* Save custom select options | |
* | |
**/ | |
function acf_save_custom_select_options( $value, $post_id, $field ) { | |
if ( ! $field['allow_custom'] || ! $field['{theme_name}_save_custom'] ) { | |
return $value; | |
} | |
// Force value to array | |
$_value = acf_array( $value ); | |
// Vars | |
$values = array(); | |
$choices = $field['choices']; | |
// Updater | |
$update = false; | |
// Construct Choices | |
foreach ( $_value as $v ) { | |
// Explode value | |
$_v = explode( ' : ', $v ); | |
$values[] = $_v[0]; | |
// value : text wasn't found | |
if ( ! isset( $_v[1] ) ) { | |
$_v[1] = $v; | |
} | |
// ignore if already exists | |
if ( isset( $choices[ $_v[0] ] ) ) { | |
continue; | |
} | |
$update = true; | |
// unslash & sanitize (remove tags) value | |
$_v[0] = wp_unslash( $_v[0] ); | |
$_v[0] = sanitize_text_field( $_v[0] ); | |
// unslash & sanitize (remove tags) text | |
$_v[1] = wp_unslash( $_v[1] ); | |
$_v[1] = sanitize_text_field( $_v[1] ); | |
// append | |
$choices[ $_v[0] ] = $_v[1]; | |
} | |
if ( $update ) { | |
// Inspired by Checkbox field | |
$selector = $field['ID'] ? $field['ID'] : $field['key']; | |
$field = acf_get_field( $selector ); | |
// bail early if no ID (JSON won't be updated) | |
if ( $field['ID'] ) { | |
$field['choices'] = $choices; | |
// Save field choices | |
acf_update_field( $field ); | |
} | |
} | |
if ( is_array( $value ) ) { | |
return $values; | |
} | |
return $values[0]; | |
} | |
add_filter( 'acf/update_value/type=select', 'acf_save_custom_select_options', 10, 3 ); | |
/** | |
* Add "Save custom" option to field settings | |
* The main save_custom doesn't work | |
* | |
**/ | |
function acf_add_save_custom_select_option( $field ) { | |
acf_render_field_setting( | |
$field, | |
array( | |
'label' => __( "Save 'custom' values to the field's choices", 'acf' ), | |
'name' => '{theme_name}_save_custom', | |
'type' => 'true_false', | |
'ui' => 1, | |
'message' => __( 'Save Custom', 'acf' ), | |
'conditions' => array( | |
'field' => 'allow_custom', | |
'operator' => '==', | |
'value' => 1, | |
), | |
) | |
); | |
} | |
add_filter( 'acf/render_field_settings/type=select', 'acf_add_save_custom_select_option' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment