I am trying to create a Facebook JS-SDK based auto login feature. When user is “Connected” passing FbID and aother user data to an ajax function which creates the session cookie. Cookie is created (I can see "wordpress_logged_in_.... cookie"
in the browser inspector) but when I reload the page the user is still logged out.
Do you have idea why?
JavaScript
function ajaxloginFB(uid,email,first_name,last_name) {
data = "uid=" + uid + "&" + "name=" + last_name + " " + first_name + "&" + "email=" + email + "&" + $.param({ action: 'facebook_login', nonce: ajax_object.ajaxnonce });
$.ajax({
url : ajax_object.ajaxurl,
type: "post",
data : data,
success:function(response){
var response = $.parseJSON(response);
if (response.success == true){
window.location.reload();
}
}
});
}
PHP
add_action( 'wp_ajax_facebook_login', 'facebook_ajax_login_or_register' );
add_action( 'wp_ajax_nopriv_facebook_login', 'facebook_ajax_login_or_register' );
function facebook_ajax_login_or_register(){
$uid = sanitize_text_field( $_POST['uid'] );
$args = array(
'meta_key' => 'fbuid',
'meta_value' => $uid,
'meta_compare' => '=',
);
$fb_user = get_users($args);
$current_user_id = $fb_user[0];
wp_set_auth_cookie( $current_user_id, true );
$response[success] = true;
echo json_encode($response);
die();
}
2 s
I add one function wp_set_current_user for setting up current user.
add_action( 'wp_ajax_facebook_login', 'facebook_ajax_login_or_register' );
add_action( 'wp_ajax_nopriv_facebook_login', 'facebook_ajax_login_or_register' );
function facebook_ajax_login_or_register(){
$uid = sanitize_text_field( $_POST['uid'] );
$args = array(
'meta_key' => 'fbuid',
'meta_value' => $uid,
'meta_compare' => '=',
);
$fb_user = get_users($args);
$current_user_id = $fb_user[0];
wp_set_current_user($current_user_id);//Set current user
wp_set_auth_cookie( $current_user_id, true );
$response[success] = true;
echo json_encode($response);
die();
}
I’m not tested this so let me know if still you facing same issue.