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 am trying to use Facebook login to register users on my blog, but after users are logged into their Facebook account, their account is still not created in WordPress. I would like to have the users registered by taking their Facebook email and creating a random password. After the user is registered, they should be automatically logged in and sent to the profile page where they can update their name, add some custom user meta data and a short bio. The code for the Facebook login integration with WordPress I'm using is below:

1- // This is the login button that goes in my index/page

<a id="FbConnect" class="join-facebook" href="#">Rejoignez-nous sur facebook</a>

2- // This goes in my functions.php

//create facebook href button
function FbC_head(){
    if( is_user_logged_in() ) return;
    ?>
    <div id="fb-root"></div>
    <script>
        window.fbAsyncInit = function() {
            FB.init({
                appId  : 'APP_ID', //have already registered the facebook app, so that's not an issue
                status : true,
                cookie : true
            });
        };
        (function() {
            var e = document.createElement('script');
            e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
        }());
    </script>
    <?php
}
add_action( 'wp_head', 'FbC_head' );//end

//load jquery if needed
function FbC_enqueue_scripts(){
    wp_enqueue_script( 'jquery' );
}
//add_action( 'wp_enqueue_scripts', 'FbC_enqueue_scripts');//end

//event handler in footer
function FbC_footer(){
    ?>
    <script>
        $('#fbLogin').click(function() {
            FB.getLoginStatus(function(response){
                if(response.status !== 'connected') {
                    //console.log(response.authResponse);
                    FB.login(function(fbresponse) {
                        //console.log(response.authResponse);              
                        if(fbresponse.status=="connected") {
                            response = fbresponse;
                            $('#fbLogin').click();
                        }
                    }, {scope: 'email'});
                }
                if(!response.authResponse) {
                    return;
                }
                FB.api('/me', function(resp) {
                    var data = {
                        authResp : response.authResponse,
                        userResp : resp
                    };
                    //console.log(data);
                    jQuery.ajax({
                        method : 'GET',
                        url : '<?php echo dirname( get_bloginfo('stylesheet_url') ) ?>/checkFB.php?callback=?',
                        data : data,
                        dataType : 'jsonp',
                        jsonpCallback : 'reply',
                        contentType : 'application/json',
                        success : function(resp) {
                            //console.log(resp);
                            if(resp.status == "Success")
                                window.location.reload();
                            else
                                console.log(resp.errors);
                        },
                        error : function(e) {
                            console.log(e);
                        }
                    });
                });        
            });
        });
    </script>
    <?php
}
add_action( 'wp_footer', 'FbC_footer' );//end

3- // Finally this is the function to do the registration and named according to 1- (checkFB.php)

//don't worry I don't wanna show this on http://wordpress.stackexchange.com/!
require_once('/this_is_the_path_to_my_server_/wp-load.php');
require_once('/this_is_the_path_to_my_server_/wp-config.php');

/*
$_REQUEST is sent with 2 arrays. We will retrieve the ID and then start checking.
*/
$login = $_REQUEST['userResp']['id'];

//Check if the username exists already
$id = username_exists($login);
$errors = array();

//Case 1 : When the ID doesn't exist.
if(!$id) {
    $email = $_REQUEST['userResp']['email'];
    $existingID = email_exists($email);
    //Case 1 confirmed : If the email also does not exist, we can proceed with registration.
    if(!$existingID) {
        $pass = wp_generate_password( $length=12, $include_standard_special_chars=false );
        $userData = array();
        $userData['user_login'] = $login;
        $userData['user_email'] = $email;
        $userData['user_password'] = $pass;
        $userData['user_nicename'] = $_REQUEST['userResp']['first_name'] .' '. $_REQUEST['userResp']['last_name'];
        $userData['first_name'] = $_REQUEST['userResp']['first_name'];
        $userData['last_name'] = $_REQUEST['userResp']['last_name'];
        $insertStatus = wp_insert_user($userData);
        if(is_wp_error($insertStatus)) {
            $errors = array_merge($errors, $insertStatus->getErrorMessages());
        }
        else {
            wp_set_auth_cookie($insertStatus, true);
        }       
    }
    //Case 2 : When the email ID the user has attached to his FB account is also registered here.
    else {
        $userFB = get_user_meta($existingID, 'fbid', true);
        //if a user is already attached to the email.
        if(!empty($userFB)) {
            //Case 2a : Here we match the Facebook ID of the user to the facebook ID of the email ID.
            if($userFB == $login)
                wp_set_auth_cookie($existingID, true);
            else {
                array_push($errors, __("Another Facebook ID seems to be attached to your account. Please check."));
            }
        }
        //Create the link between the user's email ID and the facebook ID for the first time, and log him in.
        else {
            if(!add_user_meta($existingID, 'fbid', $login, true)) {
                array_push($errors, __("Sorry! We were unable to link your FB account."));
            }
            else {
                wp_set_auth_cookie($existingID, true);
            }
        }
    }
}       
//Case 3 : When the user is already registered
else {
    wp_set_auth_cookie($id, true);
}

$resp = array();
if(!count($errors)) {
    $resp['status'] = "Success";
    $resp['loggedIn'] = true;
    $resp['errors'] = $errors;
}
else {
    $resp['status'] = "Failure";
    $resp['loggedIn'] = false;
    $resp['errors'] = $errors;
}
echo "reply(".json_encode($resp).")";
share|improve this question

Your Answer

 
discard

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

Browse other questions tagged or ask your own question.