Created
April 18, 2018 14:50
-
-
Save davebonds/36d99895599bd735d281b0e96976373d to your computer and use it in GitHub Desktop.
ManageWP snippet: Finds WP user with specific username and updates their password using wp_insert_user to bypass user notification email
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Gets all users, if username is my_username, updates password with the provided. | |
*/ | |
function get_users_and_update_info() { | |
// Build our args for get_users, search for my_username. | |
$args = array( | |
'search' => 'my_username', | |
); | |
// If multisite, search in the current blog ID (which should be the primary site). | |
if ( is_multisite() ) { | |
$args = array_merge( $args, | |
array( | |
'blog_id' => $GLOBALS['blog_id'], | |
) | |
); | |
} | |
// Find that user. | |
$users = get_users( $args ); | |
// Loop through the returned array of WP_User objects. | |
// If login matches my_username, update the password with wp_insert_user | |
foreach ( $users as $user ) { | |
if ( 'my_username' === $user->user_login ) { | |
// Set the new password here. | |
$new_password = 'bloomin-onion'; | |
// Build the user data array. Hash the password. | |
$userdata = array( | |
'ID' => $user->ID, | |
'user_pass' => md5( $new_password ), | |
'user_login' => $user->user_login, | |
// Uncomment below to also update email address. | |
// 'user_email' => '[email protected]', | |
); | |
// Use wp_insert_user to bypass sending of user notification emails. | |
$user_id = wp_insert_user( $userdata ); | |
// If it's not an error, update was successful. | |
if ( ! is_wp_error( $user_id ) ) { | |
echo 'user (ID: ' . $user_id . ') updated successfully.'; | |
} else { | |
echo $user_id->get_error_message(); | |
} | |
return; | |
} | |
} | |
} | |
get_users_and_update_info(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment