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

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