'',
'default_value' => '',
'allow_null' => 0,
'multiple' => 0,
);
}
public static function render_settings( $field, $prefix ) {
?>
isset( $raw['choices'] ) ? str_replace( array( "\r\n", "\r" ), "\n", sanitize_textarea_field( wp_unslash( $raw['choices'] ) ) ) : '',
'default_value' => isset( $raw['default_value'] ) ? sanitize_text_field( wp_unslash( $raw['default_value'] ) ) : '',
'allow_null' => ! empty( $raw['allow_null'] ) ? 1 : 0,
'multiple' => ! empty( $raw['multiple'] ) ? 1 : 0,
);
}
/**
* Parse the raw "value : Label" textarea into an assoc array.
* Used later (Phase 2) when rendering the actual select on a post.
*
* @param string $raw_choices Raw textarea content.
* @return array
*/
public static function parse_choices( $raw_choices ) {
$choices = array();
$lines = preg_split( '/\r\n|\r|\n/', (string) $raw_choices );
foreach ( $lines as $line ) {
$line = trim( $line );
if ( '' === $line ) {
continue;
}
if ( strpos( $line, ':' ) !== false ) {
list( $value, $text ) = array_map( 'trim', explode( ':', $line, 2 ) );
} else {
$value = $line;
$text = $line;
}
$choices[ $value ] = $text;
}
return $choices;
}
public static function render_input( $field, $value, $name ) {
$choices = self::parse_choices( $field['choices'] ?? '' );
$multiple = ! empty( $field['multiple'] );
if ( null === $value ) {
$value = $field['default_value'] ?? '';
}
// Normalize to an array for uniform "is this selected" checks below,
// whether the field is single or multiple select.
$selected = $multiple ? (array) $value : array( $value );
printf(
'';
}
public static function sanitize_value( $raw_value, $field ) {
$choices = self::parse_choices( $field['choices'] ?? '' );
if ( ! empty( $field['multiple'] ) ) {
$raw_values = is_array( $raw_value ) ? $raw_value : array();
$clean = array();
foreach ( $raw_values as $one ) {
$one = sanitize_text_field( $one );
if ( array_key_exists( $one, $choices ) ) {
$clean[] = $one;
}
}
return $clean;
}
$raw_value = is_array( $raw_value ) ? '' : sanitize_text_field( $raw_value );
return array_key_exists( $raw_value, $choices ) ? $raw_value : '';
}
}