I am using ajax to login users to wp like this:
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'loadingmessage' =>__('Logging you in')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
global $current_user;
get_currentuserinfo();
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-login-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon( $info, false );
if ( is_wp_error($user_signon) ){
echo json_encode(array('loggedin'=>false, 'message'=>'Login failed'));
}
else {
$user_id = $user_signon->ID;
wp_set_auth_cookie( $user_id, true );
wp_set_current_user($user_id);
$current_user = wp_get_current_user();
print_r($current_user);
$this_user_role = $user_signon->roles[0];
$this_user_admin = $user_signon->caps['administrator'];
if ( $this_user_role == "administrator" && $this_user_admin == "1" ) {
echo json_encode(array('loggedin'=>true, 'redirectto'=>home_url().'/wp-admin', 'message'=>'Login success'));
}
else {
echo json_encode(array('loggedin'=>true, 'redirectto'=>home_url(), 'message'=>'Login success'));
}
}
exit();
}
And thing is that I see that ajax reply "print_r($current_user);" is printing out user details and that seems to be working, but by some miracle cookies are not set and when page is reloaded it no user is login !?
When I run only this piece of code on my custom login page:
wp_set_auth_cookie( 1, true );
it works, but when I run it through ajax - it doesn't !? I am a little confused because I am using same function on 7 different (NON_MULTISITE) installs and all works like a charm. So my question is - what is going on ?