WP - trying to use `wp_dropdown_users( )` as custom user profile field

Viewed 679

I have update to my user profile page to include several select fields with no problem, but I'm not sure how to parse wp_dropdown_users( ) in a way that I can save the selected value to the profile.

Currently I have this as my markup:

<tr>
    <th>
        <label for="user"><?php _e('Select associated user', 'mv'); ?></label>
    </th>
    <td>
        <?phpwp_dropdown_users(); ?><br />
        <span class="description"><?php _e('Please enter the ADOC\'s name.', 'mv'); ?></span>
    </td>
</tr>

and I'm trying to save it like so:

function save_custom_userprofile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) )
    return FALSE;
    update_usermeta( $user_id, 'user', $_POST['user'] );
}
add_action( 'personal_options_update', 'save_custom_userprofile_fields' );
add_action( 'edit_user_profile_update', 'save_custom_userprofile_fields' );

The markup gives me the select, but when I try to save the profile, that select reverts back to the value of the first option.

Any help or guidance on this is, as always, greatly appreciated!

2 Answers

So first of all the function you are using to save the field is deprecated.

See: https://developer.wordpress.org/reference/functions/update_usermeta/

Otherwise, you are doing it right. You only need to retrieve the saved value and supply it as selected parameter to wp_dropdown_users function.

So something like this will do,

Code for Showing Field

function new_user_profile_fields( $user ) 
{ 
    $selected = get_user_meta( $user->ID, '_custom_dropdown_user', true );

    ?><tr>
        <th>
            <label for="user"><?php _e('Select associated user', 'mv'); ?></label>
        </th>
        <td>
            <?php wp_dropdown_users( array( "selected" => $selected ) ); ?><br />
            <span class="description"><?php _e('Please enter the ADOC\'s name.', 'mv'); ?></span>
        </td>
    </tr><?php 
}
add_action( 'show_user_profile', 'new_user_profile_fields' );
add_action( 'edit_user_profile', 'new_user_profile_fields' );

Code for Saving Field

function save_new_user_profile_fields( $user_id ) 
{
    if ( !current_user_can( 'edit_user', $user_id ) ) { 
        return false; 
    }

    update_user_meta( $user_id, '_custom_dropdown_user', $_POST['user'] );
}
add_action( 'personal_options_update', 'save_new_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_new_user_profile_fields' );
Related