Tutorial - How to Login Via Facebook in Your WordPress Blog

Tutorial - How to Login Via Facebook in Your WordPress Blog

Today I am creating a portal wordpress plugin. The first thing I think is important in a portal is user management. And with that comes user registration. To make it as smooth as possible I decided to integrate Facebook login support.

Of course there are plugins for this and I have successfully used Janrain in the past. But it’s kind of heavy and setup takes a bit. And maybe you need a custom solution, then this is the tutorial for you.

First, you need to grab the PHP SDK from GitHub – here

Then, you need to go to your Facebook App Dashboard and create a new app.

You need to state that you need it for Facebook Login and input the address of your site.

Then you need to copy the sdk source in a folder of your theme named facebooksdk and in your functions.php.

include_once( TEMPLATEPATH . '/facebooksdk/facebook.php' );

At the start you just need to include the sdk

$facebook = new Facebook(array(
  'appId'  => 'xxx',
  'secret' => 'xxx',
));

We will then input the APP ID and secret you get from Facebook

global $current_user;
get_currentuserinfo();
if($current_user->ID==0){

After this we try to see if the user is not logged in with the above code

global $facebook;
    $fbuser = $facebook->getUser();
    if ($fbuser) {
      try {
        // Proceed knowing you have a logged in user who's authenticated.
        $user_profile = $facebook->api('/me');
      } catch (FacebookApiException $e) {
        error_log($e);
        $fbuser = null;
      }
    }

We try to see if the user has logged in via facebook ( via a button we’ll add later ) and if it has done so, we capture it’s info and mail.

    if(isset($_GET['loggedout']) && $_GET['loggedout']==true){
        $facebook->destroySession();        $fbuser = null;
    }

if user has logged out, let’s end the facebook session too.

    if ($fbuser) {
        //echo 'ceva';
        
        $fb_registerpage_name = __('Facebook Register', 'bloora');
        $fbpage = get_page_by_title( $fb_registerpage_name );
        //print_r($page);
        //print_r();
        if(isset($user_profile['email'])){
            $user_name = $user_profile['email'];
            $user_email = $user_profile['email'];
            $user_id = username_exists( $user_name );
            if ( !$user_id and email_exists($user_email) == false ) {
                    $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
                    $user_id = wp_create_user( $user_name, $random_password, $user_email ); 
                    wp_set_current_user( $user_id );
                    wp_set_auth_cookie( $user_id );
                    $facebook->destroySession(); 
                    //echo 'ceva';
                    //print_r($user_profile);
            } else {
                    $random_password = __('User already exists.  Password inherited.');

                    wp_set_current_user( $user_id );
                    wp_set_auth_cookie( $user_id );
                    $facebook->destroySession(); 
            }
        }else{
            //print_r($fbpage);
            if(!is_admin() && isset($_POST) && count($_POST) > 0){
                //print_r($_POST);
                if($fbpage){
                    //echo 'ceva';
                    //ob_start(); header("Location: ".get_permalink($page->ID));
                    echo '';
                }else{
                    // Create post object
                    $my_post = array(
                      'post_title'    => $fb_registerpage_name,
                      'post_content'  => 'This is my post.',
                      'post_status'   => 'publish',
                      'post_type'   => 'page',
                      'post_author'   => 1
                    );

                    // Insert the post into the database
                    $fbpage = wp_insert_post( $my_post );
                    echo '';
                    //echo 'ceva';
                }
            }
        }
    }

The above long process will create an user for the visitor logged in via facebook with his mail as the username and log him automatically. If the user already exists in the wordpress database, it will just log him in.

Next, in the else clause, is a B plan, if the API does not have access to the email of the facebook user, it will take him to a page ( create it if it does not exist ) where he can manually input it’s mail. But there is no reason this should happen so I have not insisted on this, nor created the functionality. Just left a starting point in case I ( or anyone ) needs it – a form that reads the mail and sends it the admin should be instead of the ‘This is my post.’ string.

}

We close the if current user ID == 0 clause and that should be all for functionality.

global $facebook;
$fbuser = $facebook->getUser();
if ($fbuser) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
    $fbuser = null;
  }
}
if ($fbuser) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
  $loginUrl = $facebook->getLoginUrl(array('scope' => 'email'));
}
//echo 'fbuser'; print_r($user_profile);
                                //print_r($facebook); echo 'ceva';
                ?>          
    
      
    
      
    

All is left is include the button to login / logout from facebook. Above is the syntax.