How to set and get multiple selection values ​​using the Wordpress settings API for the theme options page?

I want to use the "multiple select" field for a field on a topic’s parameters page using API parameters.

I tried with the code below, but could not save all the selected values, but only the last selected one is saved.

add_action('admin_menu', 'create_theme_options_page');

function create_theme_options_page() {  
add_options_page('Theme Options', 'Theme Options', 'administrator', 'inc/site-options.php', 'build_options_page');
}

add_action('admin_init', 'register_and_build_fields');

function register_and_build_fields() {   
register_setting('plugin_options', 'plugin_options', 'validate_setting');
add_settings_field('clusters', 'Choose Clusters to show:', 'cluster_setting', __FILE__, 'site_section');
} 

function cluster_setting() {  
$options = get_option('plugin_options');

echo "<select name='plugin_options[clusters]' multiple='multiple'>
<option value='location'>Location</option>
<option value='role'>Role</option>
<option value='functional'>Functional Area</option>
<option value='industry'>Industry</option>
</select>"
}

How can I select multiple values ​​from a select element and save them.

Any help would be appreciated.

+2
source share
1 answer

try using

<select name='plugin_options[clusters][]' multiple='multiple'>

instead of this. This ensures that the value of the clusters is saved as an array instead of a string.

+4
source

All Articles