Nad Nad - 1 year ago 143
PHP Question

Wordpress - Custom Change Password page

I'm trying to create custom page for Change Password under Profile. When I store/update the new user password(already change to hash value), it will logout automatically. The new password can be use to login again. Is there any way to update user password without logout afterward? I would like to avoid using plugin...Below are my code:-

<form method='post' action='changepassword'>
<div class='mypageMyDetailsBox'>
<span class='titleSub'>Password</span>
<table width='90%' align="center">
<td width='40%'>Current Password</td>
<td width='60%'><input type='text' name='currentpassword' size='70'></td>
<td>New Password</td>
<td><input type='text' name='newpassword' size='70'></td>
<td>Confirm New Password</td>
<td><input type='text' name='confirmpassword' size='70'></td>

<div align='center'>
<input type='submit' name='submit_update' value='Update' class='subUpt'>
if (isset($_POST['submit_update'])) {

$currentpassword = $_POST['currentpassword'];
$newpassword = $_POST['newpassword'];

require_once ABSPATH . 'wp-includes/class-phpass.php';
$wp_hasher = new PasswordHash( 8, true );

$user_info = get_userdata($currentUserID);
$user_pass = $user_info->user_pass;

if($wp_hasher->CheckPassword($currentpassword, $user_pass)) {
$passhash = wp_hash_password($newpassword);
$upd = $wpdb->query("UPDATE wp_users SET user_pass = '".$passhash."' WHERE ID = ".$currentUserID." LIMIT 1");
if ($upd) {
} else {
//Password not match

Thank you in advance.

Answer Source

You should try using wp_set_password, instead of directly using WP_Query. While I haven't tested it specifically, it should update the password and not require you to logout and log back in.

EDIT: The problem is the cookie becomes invalid. You'll need to set/reset cookies using wp_set_auth_cookie. Try adding this:

    if (wp_signon(array('user_login'=>$user->user_login,'user_password'=>$_POST['admin_pass1']),false)):
    wp_set_auth_cookie( $current_user_id, true);