Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
2  
Why did you cross post it on Stack Overflow? Do not do this again. Chose your target site and stick with it. –  kaiser Aug 2 at 9:34

2 Answers 2

up vote 6 down vote accepted

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');
share|improve this answer

You need to include wp-includes/user.php file when you are using ajax for user related functions.

 function check_username() {

   require_once (ABSPATH.'/wp-includes/user.php');
   $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');
share|improve this answer
3  
When using Ajax API in the right way, manually loading user.php is needed only if SHORTINIT constant is true, because admin-ajax.php load wp-load.php, that load wp-config.php, that load wp-settings.php that on its turn load user.php. –  G. M. Aug 2 at 8:57
    
This won't work - $return isn't set. –  kaiser Aug 6 at 8:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.