MultiSelect Example with wp_dropdown_categories

In WordPress we do not have a form element wp_dropdown_categories for multiple usage. That means we need to hack this functionality into wp_dropdown_categories.

See the Gist Example

Get the Terms with wp_dropdown_categories

In line 40 I use the wp_dropdown_categories function to get a select box with all categories.

wp_dropdown_categories can be used with custom post types. See  http://codex.wordpress.org/Function_Reference/wp_dropdown_categories for a list of all attributes.

$dropdown = wp_dropdown_categories($wp_dropdown_categories_args);<br>

Change the dropdown into an MultiSelect

Next on line 42 I create a multiple select box with str_replace:

$dropdown = str_replace('id=', 'multiple="multiple" id=', $dropdown);<br>

Display saved values

Last step starting on line 44 is to run through all selected options with a foreach and add the selected attribute with str_replace:

if (is_array($taxonomy_default)) {
	foreach ($taxonomy_default as $key => $post_term) { 
		$dropdown = str_replace(' value="' . $post_term . '"', ' value="' . $post_term . '" selected="selected"', $dropdown); 
	}
 } else { 
	$dropdown = str_replace(' value="' . $taxonomy_default . '"', ' value="' . $taxonomy_default . '" selected="selected"', $dropdown);
}	

This is a work around and hopefully WordPress will provide a attribute in the future to use wp_dropdown_categories with multiple selections.

Still need help? Contact Us Contact Us