How can I set and get the values of a multiple select with the WordPress settings API for a theme options page?

I want to use a ‘multiple select field’ for a field in the theme option page using settings API.

I tried with the below code but unable to save all the selected values, it only saves last one selected.

Read More
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 the select element and save them.

Any help will be appreciated.

Related posts

Leave a Reply

1 comment

  1. try using

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

    instead. This will ensure that the clusters value is saved as an array instead of a string