One of the local businesses I work with uses their WordPress site to allow their customers to login and manage some information relating to their company via WordPress.
We recently were adding some new users to the site and wanted to send out a welcome email with some instructions for setting up their account, along with a password reset link. While we could of just customized the password reset email using the retrieve_password_message filter and then manually done the password reset for each email, the plan was to send the emails out using a Mailchimp marketing campaign, so we could track opens, clicks, and other information.
So, it was necessary to get a list of password reset links. The below is a quick function that you can use to generate password reset links without sending the WordPress Lost Password Message to the user.
It is setup to take an array of User IDs. If there is an error, the error will be printed and no links generated. Otherwise, it prints the user’s info, along with the password reset link.
This was tested on WordPress 4.9.7 and uses code from the default retrieve_password() function found in wp-login.php. However, it should work with other versions of wordpress as well.
Note that running the below multiple times for the same user will generate a unique reset url each time and invalidate any old/pending password reset urls!
<?php /* An array of user_ids tied to the numeric ID of the wordpress user found in wp_users table(or elsewhere on site.) */ $reset_users = array(1955521); /* Loop through each user_id in the 'reset_users' array to generate a password reset URL*/ foreach($reset_users as $user_id){ $reset_data = get_password_reset_url($user_id); /* If error, print the error message and exit*/ if( is_wp_error( $reset_data ) ) { echo $reset_data->get_error_message()."\n"; exit; } else{ echo "{$user_id}\t{$reset_data['user_data']->user_email}\t{$reset_data['user_data']->display_name}\t{$reset_data['reset_url']}\n"; } } /** * Handles retrieving a password reset URL, without sending to user. * * @return WP_Error or array with 'user_data' and 'reset_url' keys. */ function get_password_reset_url($user_id) { $errors = new WP_Error(); $user_id = intval($user_id); if($user_id <= 0){ $errors->add('bad_user_id', __("<strong>ERROR</strong>: Invalid User ID for {$user_id}")); return $errors; } $user_data = get_userdata($user_id); if($user_data === false){ $errors->add('bad_user_data', __("<strong>ERROR</strong>: Invalid User Data for {$user_id}")); return $errors; } $user_login = $user_data->user_login; $key = get_password_reset_key( $user_data ); if ( is_wp_error( $key ) ) { $errors->add('bad_user_key', __("<strong>ERROR</strong>: Invalid User Key for {$user_id}")); return $errors; } $password_reset_url = network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user_login ), 'login' ); return array('user_data'=>$user_data, 'reset_url'=>$password_reset_url); }
Add a Comment