The similar question is posted many times but actually all the questions i have searched and found are how to make dropdown categories multiple selected option.
But my question is not posted anywhere and that is how to populate multiple selected values and select them when you have selected inputs.
Let’s say i have wp_dropdown_categories
function with multiple select option.
function dropdown_language( $language = false ) {
$args = [
'show_option_all' => '',
'show_option_none' => '',
'option_none_value' => '',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
'child_of' => 0,
'hierarchical' => 1,
'depth' => 1,
'name' => 'language[]',
'id' => 'language',
'selected' => $language,
'class' => 'select2 form-control',
'taxonomy' => 'language',
'hide_if_empty' => false,
'value_field' => 'term_id',
'echo' => false
];
$cat_dropdown = wp_dropdown_categories( $args );
$cat_dropdown = preg_replace(
'^' . preg_quote( '<select ' ) . '^',
'<select required data-placeholder="Language" data-error="Please select Language" multiple="multiple"',
$cat_dropdown
);
echo $cat_dropdown;
}
So when i first open a page with this function i have a nice multiselect dropdown with select2 plugin and all works fine.
This gets saved in database as an array with multiple fields selected.
But when i want to open a page with this function again and since i have previously saved list of selected languages the $language
is not false
. It is an array of previously selected languages.
And now i need to populate selected
arg with list of values from $language
and select multiple selected fields.