Reputation: 510
I use the following code to get a list of country codes from a user and assign it to a string called 'locations.'
<input
type="text"
class="widefat code"
id="edit-menu-item-visibility-<?php echo $item_id; ?>"
name="menu-item-visibility[<?php echo $item_id; ?>]"
value="<?php echo esc_html( get_post_meta( $item_id, 'locations', true ) ); ?>" />
<?php echo 'Enter 2-digit country codes separated by commas, e.g. US,CA,SG' ?></br>
If I wanted to use the following multi-select dropdown menu instead, how could I pass the values to 'locations' as a comma separated list (string)? i.e. "US,CA,SG"
<select name="chzn-select" class="chzn-select" multiple="true">
<option value="KH">Cambodia</option>
<option value="CM">Cameroon</option>
<option value="CA">Canada</option>
<option value="SG">Singapore</option>
<option value="US">United States</option>
</select>
EDIT:
Here is how the variable currently gets to the database:
function update_option_text( $menu_id, $menu_item_db_id, $args ) {
$meta_value = get_post_meta( $menu_item_db_id, 'locations', true );
$new_meta_value = stripcslashes( $_POST['menu-item-visibility'][$menu_item_db_id] );
if( '' == $new_meta_value ) {
delete_post_meta( $menu_item_db_id, 'locations', $meta_value );
}
elseif( $meta_value !== $new_meta_value ) {
update_post_meta( $menu_item_db_id, 'locations', $new_meta_value );
}
}
UPDATE:
The selected values are now getting sent to the database. But I can seem to figure out how to keep the selected values selected after saving the form.
Here's my non-working attempt to make it work by brute force:
<option value="AF" <?php $locations = get_post_meta( $item_id, 'locations', true); if(in_array("AF", $locations ))){echo "selected='selected'";}else{echo "";} ?> >Afghanistan</option>
Am I on the right track?
Upvotes: 0
Views: 1420
Reputation: 3515
Just treat your select
box as an array like :
<select name="chzn-select[]" class="chzn-select" multiple="true">
And your PHP code :
<?php
if(!empty($_POST["chzn-select"])) {
$val = implode(",",$_POST["chzn-select"]);
}
?>
Upvotes: 3