Why are you making work hard for yourself? wp_create_user
already checks if the email/login exists, which is also why your code is “failing” – $user_id
will already be a WP_Error
, so your elseif ( is_wp_error( $newerrors ) )
never fires.
All you need is:
$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email, $capa );
if ( is_wp_error( $user_id ) ) {
wp_send_json( array(
'loggedin' => false,
'message' => $user_id->get_error_message(),
) );
}
exit;
Also note I’ve used the WordPress helper wp_send_json
, which is the correct way of sending JSON data back to the client.