Skip to content

Instantly share code, notes, and snippets.

@davebonds
Created April 18, 2018 14:50
Show Gist options
  • Save davebonds/36d99895599bd735d281b0e96976373d to your computer and use it in GitHub Desktop.
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
/**
* 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' => 'me@me.com',
);
// 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