username_exists() function can’t be access without logging in

I’m using the following function in functions.php to check if a username exists in the DB

function check_username() {
   $username = $_POST['user'];
   if ( username_exists( $username ) ) {
       $return['user_exists'] = true; 
   }
   else {
       $return['user_exists'] = false;
   }
   echo json_encode($return);
   die();
}
add_action('wp_ajax_check_username', 'check_username');

The problem is that the username_exists() function only seems to work if a user is already logged in and checks a username. I tried to check for an existing username without logging in and it just returns undefined for me.

I have no idea why this is happening and can’t find any documentation about this issue.

My question is, how do I enable a user to check if a user exists without having to log in?

Thanks

2 s
2

When using Ajax API, and you want to make the ajax callback available for non-logged users, you need to add 2 actions, "wp_ajax_{$action}" and "wp_ajax_nopriv_{$action}".

Using only the first action, the callback will be called only for logged users, using only the second it will be called only for non-logged visitors.

Try this:

function check_username() {
   $uname = filter_input( INPUT_POST, 'user', FILTER_SANITIZE_STRING );
   wp_send_json( array(
     'user_exists' => get_user_by( 'login', $uname ) ? 'true' : 'false'
   ) );
}


add_action('wp_ajax_check_username', 'check_username');
add_action('wp_ajax_nopriv_check_username', 'check_username');

Leave a Comment