QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads WordPress Frontend Facebook Login

WordPress Frontend Facebook Login

wordpress-facebook-oauth-login

This tutorial is for WordPress developers who want to integrate Facebook login button in WordPress themes. E-Commerce, Forum etc themes require you to login, providing a Facebook login button make the login process faster for users as they don’t have to fill up long forms.

Downloading and including the Facebook OAuth WordPress library

I have created a Facebook OAuth library for WordPress which handles all the tough task of Facebook OAuth login. This library also creates necessary REST API URLs required for Facebook Login.

Extract the zip file in your theme folder. Now you will have a “inc” directory in your theme folder which has all necessary files for Facebook login.

Loading Facebook OAuth WordPress library

Now you need to load the library into WordPress. Inside your theme’s “functions.php” file include

require_once("inc/facebookoauth.php");

Redriecting users

When user clicks on Sign In with Facebook button you need to redirect user to

site_url()."/wp-admin/admin-ajax.php?action=facebook_oauth_redirect"

This URL will handle all core functionality of Sign In with Facebook. Once the user has been logged in, the user will be redirected to the homepage of the website.

Creating and Installing Facebook App

Users who install your theme needs to create a Facebook App for their website.

Make sure while creating a app they provide the domain name of their website.

Once they have created a Facebook App they need to copy the App ID and App secret from Facebook App dashboard and store them as WordPress options.

Use the following option names to store the options value.

update_option("facebook_app_id", $app_id_variable);

update_option("facebook_app_secret", $app_secret_variable);

This is all you need to do to have a Facebook login button in your theme.

Let’s create a Facebook Login widget which displays a Facebook Login Button.

Facebook Login Widget

Here is the code for creating a Facebook Login Widget.

You can put this code inside a plugin also. Make sure you pack the Facebook OAuth WordPress library with your plugin also.

<?php
require_once("inc/facebookoauth.php");
class Facebook_Login_Widget extends WP_Widget
{
    public function __construct()
    {
        parent::__construct("facebook_login_widget", "Facebook Login", array("description" => __("Display a Facebook Login Button")));
    }
       
    public function form( $instance )
    {
        // Check values
        if($instance)
        {
            $title = esc_attr($instance['title']);
            $app_key = $instance['app_key'];
            $app_secret = $instance['app_secret'];
        }
        else
        {
            $title = '';
            $app_key = '';
            $app_secret = '';
        }
        ?>

        <p>
            <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'facebook_login_widget'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </p>

        <p>
            <label for="<?php echo $this->get_field_id('app_key'); ?>"><?php _e('App ID:', 'facebook_login_widget'); ?></label>
            <input type="text" class="widefat" id="<?php echo $this->get_field_id('app_key'); ?>" name="<?php echo $this->get_field_name('app_key'); ?>" value="<?php echo $app_key; ?>" />
        </p>
       
        <p>
            <label for="<?php echo $this->get_field_id('app_secret'); ?>"><?php _e('App Secret:', 'facebook_login_widget'); ?></label>
            <input type="text" class="widefat" id="<?php echo $this->get_field_id('app_secret'); ?>" name="<?php echo $this->get_field_name('app_secret'); ?>" value="<?php echo $app_secret; ?>" />
        </p>
       
        <?php
    }
       
    public function update( $new_instance, $old_instance )
    {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['app_key'] = strip_tags($new_instance['app_key']);
        $instance['app_secret'] = strip_tags($new_instance['app_secret']);
       
        update_option("facebook_app_id", $new_instance['app_key']);
        update_option("facebook_app_secret", $new_instance['app_secret']);
       
        return $instance;
    }
       
    public function widget( $args, $instance )
    {
        extract($args);
       
        $title = apply_filters('widget_title', $instance['title']);
        echo $before_widget;
       
        if($title)
        {
            echo $before_title . $title . $after_title ;
        }
       
        if(is_user_logged_in())
        {
            ?>
                <a href="<?php echo wp_logout_url( get_permalink() ); ?>" title="Logout"><input type="button" value="Logout" /></a>
            <?php
        }
        else
        {
            ?>
                <a href="<?php echo site_url() . '/wp-admin/admin-ajax.php?action=facebook_oauth_redirect'; ?>"><input type="button" value="Login Using Facebook" /></a>
            <?php
        }
       
        echo $after_widget;
    }
}
register_widget("Facebook_Login_Widget");

Let’s see how the above code works:

  • We first included the Facebook OAuth library.
  • Then we created a Widget which displays a Login button on frontend and displays keys input boxes on backend.
  • When users submit the widget form on backend the values are saved as WordPress options.
  • When someone clicks on the Facebook Login button on the frontend of the widget, the users are redirected to the Redirect URL as mentioned above. The redirected URL handles all the login task.

Screenshots of the Facebook login widget

enter image description here

enter image description here

Access Graph API

This library also allows you to make calls to graph API. Its stores the access token required for graph API as user meta. You can retrieve it as

get_user_meta(get_current_user_id(), 'facebook_access_token', true);

Now you can make calls to graph api using this token. By default this library has access to get only username and email address. You need to increase the permission by adding new facebook permissions to the $permission variable in facebookoauth.php file.

Complete Graph API Reference.

Refreshing Access Token

Facebook doesn’t allow you to use access token for more than 60 days. After the token has expired you need to ask the user to login again using the complete login flow.

While logging in user you can store the current time as user meta data and refresh it before 60 days. Or else you can wait until you get a 401 response error to refresh the token.

Conclusion

Now you have learnt how to create a facebook Login button. If you integrate it in your theme then you can place the button anywhere. If you integrate it in plugin then you need to put in a widget.

Oct 17, 2014Narayan Prusty
WordPress Frontend Twitter OAuth LoginStop requestAnimationFrame
Comments: 17
  1. korkut
    5 years ago

    this add-on stopped working after fb version changed

    ReplyCancel
  2. Nikhil
    6 years ago

    how to store email id ??? it does not store email when account is created.

    ReplyCancel
  3. Aparecido
    6 years ago

    Hi. I did the installation worked well? This working connection to facebook. However when you click connect, opens the window and facebook so public_profile list – the mail does not appear as an option. Also not sign up email on wordpress. Someone managed to solve or is working just right? Grateful responses.

    ReplyCancel
  4. ricardfs
    6 years ago

    Hi.

    Is it possible to make the redirection is not the home page if not where you clicked on the button?

    ReplyCancel
  5. Youssef
    7 years ago

    HI,
    i tried the first way of adding a button, so not in a widget but normal embeding.
    i downloaded the zip code i uploaded it into my theme directory and
    i added the require_once(“inc/facebookoauth.php”); into theme function.php file
    and i embeded this code into wp-login.php of my theme
    site_url().”/wp-admin/admin-ajax.php?action=facebook_oauth_redirect”

    the matter is i don’t know where to put these two lines
    update_option(“facebook_app_id”, $app_id_variable);

    update_option(“facebook_app_secret”, $app_secret_variable);

    when i click on the button it says The parameter app_id is required

    ReplyCancel
    • Narayan Prusty
      7 years ago

      You have to ask the site admin to input “facebook_app_id” and “facebook_app_secret”.

      You can create a WordPress Settings Page(http://qnimate.com/wordpress-settings-api-a-comprehensive-developers-guide/) for that.

      If you are creating facebook login button only for your site then put this code in your theme’s functions.php file.

      ReplyCancel
      • Youssef
        7 years ago

        hi,
        i tried as much as i can
        i added the full code in the php file into function.php theme file. i copy the app_id and paste it everywhere i find facebook_app_id and copy app secret code from facebook and page it in facebook_app_secret
        but the problem still same
        what shall i do?

        ReplyCancel
  6. Ramesh
    7 years ago

    How to store users email id? All code is working great but still i cant store users email id in wordpress.

    ReplyCancel
    • Narayan Prusty
      7 years ago

      Email id is stored automatically while creating account.

      ReplyCancel
      • Ramesh
        7 years ago

        I tried the above code but its not storing the email id of the users who login via Facebook. Am i missing something? please help…

        ReplyCancel
        • Rahul
          5 years ago

          If anyone having issue with fetching email id, here is the solution.

          Add “?scope=email” in “$final_url” in the facebook_oauth_redirect() function

          The final url will be:

          $final_url = “https://www.facebook.com/dialog/oauth?scope=email&client_id=” . urlencode($app_id) . “&redirect_uri=” . urlencode($redirect_url) . “&permission=” . $permission;

          Thank you

          ReplyCancel
  7. vighnesh
    7 years ago

    Hi Narayan,

    I am facing below issues.

    session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\wp-content\plugins\fb-login\fblogin.php:12) in C:\xampp\htdocs\cityhunters\wp-content\plugins\fb-login\inc\facebookoauth.php on line 3

    ReplyCancel
    • Narayan Prusty
      7 years ago

      Don’t run it on localhost. Try with a public server.

      ReplyCancel
      • vighnesh
        7 years ago

        What is the problem . I have created facebook app with local host only

        ReplyCancel
        • Narayan Prusty
          7 years ago

          I have tested it in public server therefore not sure of localhost. Anyways refer the below link for the solution for the error you are getting

          http://stackoverflow.com/questions/8812754/cannot-send-session-cache-limiter-headers-already-sent

          ReplyCancel
  8. Vincent
    8 years ago

    Does this create a new user in the WordPress as well?

    ReplyCancel
    • Narayan Prusty
      8 years ago

      Yes it does.

      ReplyCancel

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

Image8 years ago 18 Comments WordPress
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • Downloading and including the Facebook OAuth WordPress library
  • Loading Facebook OAuth WordPress library
  • Redriecting users
  • Creating and Installing Facebook App
  • Facebook Login Widget
  • Access Graph API
  • Refreshing Access Token
  • Conclusion
Related Articles
  • WordPress Frontend Twitter OAuth Login
  • Login User into WordPress without Password
  • Underscores.me Tutorial
  • WordPress Enable or Disable Auto Update
  • Creating a One Page WordPress Theme
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license