my website users register with phone number OTP. That's why they have no email address in their accounts. Today I need email address in user accounts. I use this code to add email address for new user registrations.
add_action("user_register", function ($user_id) {
$user = get_userdata($user_id);
if (empty($user->data->user_email)) {
$args = array(
"ID" => $user->id,
"user_email" => uniqid() . "@example.com",
);
wp_update_user( $args );
}
});
add_filter( 'bnfw_trigger_insert_post', '__return_true' );
But I have about 3000 users that need email address in their accounts if empty . How can I do this automatically . Can make above code to work for already registered user.
and above code generate email like this 62961a20c7f2a@exmaple.com .how can use "username" instead of uniqid()
my new code according to answer
// The Query
$user_query = new WP_User_Query( ['number' => 3500, 'paged' => 1] );
// if users were found
if ( ! empty( $user_query->get_results() ) ) {
// then for each user
foreach ( $user_query->get_results() as $user ) {
// if it already has an email, skip it
if ( ! empty( $user->user_email ) ) {
continue;
}
// otherwise, add an email here...
$args = array(
"ID" => $user->id,
"user_email" => $user->user_login . "@example.com",
);
wp_update_user( $args );
}
} else {
echo 'No users found.';
}
$user = get_user_by( 'id', $user_id );
, it's already getting the$user
from the user query in the loop, so that line is unnecessary. It's also unclear where this code is located and when it runs, I suspect you've confused my 2 pieces of code and combined them