Doing This For a Single User In The user_register
Filter
Instead of using get_userdata
in your filter, fetch the user itself as a WP_User
object via get_user_by
:
$user = get_user_by( 'id', $user_id );
This gives you access to all of the fields of WP_User
directly, e.g.:
echo $user->user_login;
Which you can then plug into your code
Doing this for all the other users
You should use WP_User_Query
to fetch an array of users that do not have emails ( assuming the email is an empty string ). This would not happen inside your filter and is a separate independent piece of code.
https://developer.wordpress.org/reference/classes/wp_user_query/
Here’s an example from the docs that loops through every user with a blank email and displays their name:
// The Query
$user_query = new WP_User_Query( [] );
// 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...
}
} else {
echo 'No users found.';
}
You can remove the echo
and replace it with your check that tests the email is empty and updates the user.
Note that since you have a lot of users, you may need to set 'number' => 200, 'paged' => 1,
in the WP_User_Query
arguments, and re-run the loop several times with paged
set to higher numbers. This is to avoid running out of memory.