修改了上述答案中的代码,以便它能够正确显示查看用户配置文件时所做的多项选择,并将“多项”属性添加到选择本身。
<?php
// Display Fields
add_action( \'show_user_profile\', \'add_multiple_choice_dropdown \' );
add_action( \'edit_user_profile\', \'add_multiple_choice_dropdown \' );
$current_selections = get_user_meta( $user->ID, \'multi_dropdown\', true );
?>
<h3>Extra profile information</h3>
<table class="form-table">
<tr>
<th><label for="multi_dropdown">The dropdown with multiple choices</label></th>
<td>
<select name="multi_dropdown[]" multiple>
<option value="first_choice" <?php echo ( !empty( $current_selections ) && in_array( \'first_choice\', $current_selections ) ? \' selected="selected"\' : \'\' ) ?>>First Choice</option>
<option value="second_choice" <?php echo ( !empty( $current_selections ) && in_array( \'second_choice\', $current_selections ) ? \' selected="selected"\' : \'\' ) ?>>Second Choice</option>
<option value="third_choice" <?php echo ( !empty( $current_selections ) && in_array( \'second_choice\', $current_selections ) ? \' selected="selected"\' : \'\' ) ?>>Third Choice</option>
</select>
<p class="description">Choose from the options above.</p>
</td>
</tr>
</table>
<?php
}
// Save fields
add_action( \'personal_options_update\', \'save_multiple_choices\' );
add_action( \'edit_user_profile_update\', \'save_multiple_choices\' );
function save_multiple_choices( $user_id ) {
if ( isset( $_POST[\'multi_dropdown\'] ) ) {
update_user_meta( $user_id, \'multi_dropdown\', $_POST[\'multi_dropdown\'] );
}
}
?>