Issue when updating the password with wp_update_user()

I am creating a plugin that has a frontend profile update portion.

If I have this code...

$userdata = array(
    'user_login'    =>   $username,
    'user_email'    =>   $email,
    'user_url'      =>   $website,
    'first_name'    =>   $first_name,
    'last_name'     =>   $last_name,
    'nickname'      =>   $nickname,
    'description'   =>   $bio,
);

global $current_user; get_currentuserinfo();
$ID=$current_user->ID;
$ID_array = array('ID' => $ID);
$userdata = $ID_array + $userdata;

$user = wp_update_user( $userdata );

...all is good; however, if I also update the password by adding 'user_pass' => $password thus changing the code to...

$userdata = array(
    'user_login'    =>   $username,
    'user_email'    =>   $email,
    'user_pass'     =>   $password,
    'user_url'      =>   $website,
    'first_name'    =>   $first_name,
    'last_name'     =>   $last_name,
    'nickname'      =>   $nickname,
    'description'   =>   $bio,
);

global $current_user; get_currentuserinfo();
$ID=$current_user->ID;
$ID_array = array('ID' => $ID);
$userdata = $ID_array + $userdata;

$user = wp_update_user( $userdata );

... I get the following error on the frontend...

Warning: Cannot modify header information - headers already sent by (output started at /home/sdglandl/public_html/home/wp-content/themes/converio/header.php:2) in /home/sdglandl/public_html/home/wp-includes/pluggable.php on line 942

The same error occurs over and over and over for multiple lines

1 answer

  • answered 2017-11-15 01:13 Andrew Schultz

    When you update the current user's password the current user's cookies are cleared. This is similar to an issue already discussed. You'll need to run this code before any HTML is rendered to prevent the headers being already set issue.

    add_action( 'wp', 'set_current_users_password' );
    
    function set_current_users_password() {
        // Get current logged-in user.
        $user = wp_get_current_user();
    
        // Change password.
        wp_set_password($new_password, wp_get_current_user()->ID);
    
        // Log-in again.
        wp_set_auth_cookie($user->ID);
        wp_set_current_user($user->ID);
        do_action('wp_login', $user->user_login, $user);
    }