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.

  • Mouad
    November 15, 2013 at 11:46 pm

    nice work

    you can update info with meta user

    update_user_meta($user_id, ‘user_id_fb’, $user_profile[‘id’]);
    update_user_meta($user_id, ‘display_name’, $user_profile[‘name’]);
    update_user_meta($user_id, ‘first_name’, $user_profile[‘first_name’]);
    update_user_meta($user_id, ‘last_name’, $user_profile[‘last_name’]);
    update_user_meta($user_id, ‘user_nicename’, sanitize_title($user_profile[‘username’]));
    update_user_meta($user_id, ‘authorimgr’, $user_profile[‘pic_small’]);
    update_user_meta($user_id, ‘description’, ”);
    update_user_meta($user_id, ‘rich_editing’, ‘true’);
    update_user_meta($user_id, ‘comment_shortcuts’, ‘false’);
    update_user_meta($user_id, ‘admin_color’, ‘fresh’);
    update_user_meta($user_id, ‘use_ssl’, 0);

  • raz
    December 21, 2013 at 2:27 am

    It does not work , it does not create a new user , it does not log out of the website only out of facebook. Other than that great work. I put the whole code in functions.php exept the login and logout buton witch is in footer.php

  • raz
    December 21, 2013 at 2:32 am

    If the Facebook name is different than the wordpress user but they have the same email adress it does not login or logout.

  • cobaltfishfood
    March 11, 2015 at 11:03 am

    This was the first place that told me the answer. I have added you to my bookmark list to check out new articles you post

  • canarias-auto
    March 15, 2015 at 9:48 pm

    Merely wanna comment that you have a very decent site, I enjoy the pattern it actually stands out.

  • Dedicated Server
    March 16, 2015 at 3:32 am

    My buddy proposed I’d potentially this way internet site. Your dog once were totally suitable. This kind of post absolutely created the morning. You simply can’t take into consideration the way in which a good deal period I had wasted for this details! Appreciate it!

  • joe
    April 5, 2015 at 12:43 am

    I have added you to my bookmark list to check out new articles you post
    thank you for usefull article

  • azheartcare
    May 30, 2015 at 11:23 am

    Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information. 

  • autoconfrontation
    June 2, 2015 at 11:18 pm

    I enjoy what you guys are usually up too. This type of clever work and exposure! Keep up the amazing works guys I’ve incorporated you guys to my personal blogroll.

  • Dravislins
    July 16, 2015 at 1:46 am

    viagra daily overcomes meth ed
    [url=http://viagra-withoutadoctorsprescriptions.com]viagra without a prescription
    [/url] viagra 10mg or 20mg location
    viagra without a doctor prescription
    – can woman use viagra
    viagra black review

Leave a comment

Your email address will not be published

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

2 + 1 =