Function username_exists() can’t be accessed without logging in to wordpress

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.

Read More

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

Related posts

Leave a Reply

1 comment

  1. try this

      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');
          add_action( 'wp_ajax_nopriv_check_username', 'check_username' );
    

    wp_ajax_check_username – anonymous / non-logged in visitors

    wp_ajax_nopriv_check_username– logged in users