How can I set and get the values of a multiple sel

2019-07-01 12:06发布

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.

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.

1条回答
Luminary・发光体
2楼-- · 2019-07-01 12:53

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

查看更多
登录 后发表回答