php wordpress password change - logging me out!

前端 未结 6 1180
栀梦
栀梦 2020-12-11 20:01

I\'m trying to build a simple wordpress password change script of my own (well, based on a plugin really) - the password is successfully changed - but it logs me out after t

6条回答
  •  眼角桃花
    2020-12-11 20:21

    Was linked here from another post, and wanted to give an updated solution to this problem, as some of these solutions (especially modifying wpdb->query directly) aren't best practice anymore.

    Update the user's password using wp_set_password(), and then log the user back in, using wp_signon().

    wp_signon will create the authentication cookie for you, as other users have suggested, but in a much more streamlined way.

    function create_new_password_for_user($new_password){
        //Get the current user's details, while they're still signed in, in this scope.
         $current_user = wp_get_current_user();
         $current_user_id = $current_user->ID;
         $users_login = $current_user->user_email;
    
        //set their new password (this will trigger the logout)
        wp_set_password($new_password, $current_user_id);
    
        //setup the data to be passed on to wp_signon
        $user_data = array(
                'user_login'     => $users_login,
                'user_password'    => $new_password,
                'remember'        => false
            );
    
        // Sign them back in.
        $result = wp_signon( $user_data );
    
        if(is_wp_error($result)){
          //do something with an error, if there is one.
        }else{
          //do something with the successful change. 
        }
    }
    

提交回复
热议问题