In this tutorial, we will see how to write a simple WordPress plugin in order to Login and Register your users right on your WordPress site using the Facebook API. It is very easy to do and we will go through each step one by one.

You need to have basics in PHP, WordPress development, CSS and HTML. But nothing tricky here.

You can find the complete plugin on Github: Plugin repository

Note that this is a first part, as you will see at the end, there are many things that can be improved.

The authentication flow from Facebook is quite simple:

  • We use the Facebook SDK to generate a login link to redirects toward Facebook’s server.
  • If everything is good and the user agrees to let our application get some details. We are redirected back to our WordPress site.
  • During the redirection, Facebook gives us a temporary “Access Token”.
  • We use this token to ask the Facebook API to get the user’s details: ID, Name, Email…
  • We handle the data in WordPress by either connecting the user if there was a previous connection or by creating a new account.

What is the goal?

We want to provide our users a very simple way to login and register to WordPress. Without email, username or password to enter in order to log in. Just a single button to click.

The easiest way will be to create a new shortcode which will display a Login/Register button and any error that should be displayed. So you can use it in any page / post / widget  or theme template using the do_shortcode function.

The shortcode will display nothing if the user is currently logged in. You might want to change that behavior.

We will use a plugin to wrap our code so it can work in any site. This plugin will be using the Facebook SDK and an object oriented coding style.

Feel free to change all the “alka” word  with your organization’s name.

Step 1: Building our plugin and importing the Facebook PHP SDK

First, we need to create a new plugin so our code is run by WordPress. Create a new directory “alka-facebook” (in wp-content/plugins/) that will hold all our files. Then, let’s get started! Create a new alka-facebook.php file:

You can now enable the plugin in Plugins > Alka Facebook > Activate. All our code will now be executed by WordPress, which is good.

Then, we can now import the Facebook PHP Sdk which will help us to make our calls to the Facebook API using PHP.

There are several ways to import it, the easiest one in WordPress is to download the SDK, rename the folder as facebook-sdk and move it to our plugin’s directory:

Now, we need to call the Facebook Sdk files required by the authentication actions that will be done within our plugin.

Just add the following to the top of the plugin’s file, right after the plugin header:

Step 2: creating our Facebook Application

Secondly, in order to make API calls to the Facebook API, we obviously need to get some access. So Facebook knows who is making the calls and requesting the user details.

You can do that by going on the Facebook Apps page: https://developers.facebook.com/apps.

  • Click the “Add a new App” button
  • Set up the name and create your APP
  • Enable the Products > Facebook Login 
  • Add your Callback URL, which is http://yoursite.com/wp-admin/admin-ajax.php?action=alka_facebook you definitely need to change yoursite.com with your site’s URL.

  • Go to the Settings to get your App Id and App Secret 

We can now save them in our Class safely:

We are now ready to use Facebook API safely from our site.

Step 3: Creating our Shortcode

Thirdly, we will create a very simple shortcode to display our button, you can add options to this shortcode to go further we won’t do it in this tutorial though.

The shortcode is added using the “add_shortcode” WordPress function in our constructor and calls a method “renderShortcode“, which has a pretty good name according to how we will use it.

You can now use [alka_facebook /] in your editor in any page and save. For testing purpose, you can now log out.

Step4: Connecting to the API

Next, we will now create a connection between our plugin and the Facebook API using our Facebook App’s details. In order to achieve this, we will create a new method to initialize the connection as it will be called several times, we return a Facebook instance:

Thus, we can now use the SDK to get a login/register URL that will be used whenever the user clicks our button. Note that we use the PHP session to pass the data through all the methods and Facebook’s authentication steps:

So, we can now use this URL in our button (renderShortcode) method:

Our Facebook signing button now redirects us to Facebook, we are also redirect back to our callback URL. Yi hay!

Step 5: The callback

Lastly, the Callback is the code run by our plugin whenever an user is done with the Facebook dialog. He is redirected back to our site. For this matter, we created a new URL (already used earlier) http://yoursite.com/wp-admin/admin-ajax.php?action=alka_facebook which is basically a way to run our code with our own URL in WordPress. This is using the AJAX way, it would be better to use the REST API later though.

And we need to create our callback’s method. This callback decides whether the user must be logged in or registered. This is where all the magic happens!

We will introduce a bunch of new stuff first here:

  • A new “alka_facebook_messagesession variable that will handle any error or message that must be displayed back to the user.
  • A new “alka_facebook_urlsession variable to redirect our user properly after the callback. It saves the page’s URL (where the shortcode is located)
  • A new class property: $access_token to use the access token from the Facebook API
  • A new class property: $redirect_url to use our alka_facebook_url within our class
  • A  new class property: $facebook_details to use the user data returned by the Facebook URL.

Moreover, we use class properties so we can split our code in several methods and never pass anything as an argument but rather as a class property. Which is cleaner.

In order that we now add our new properties:

We can also update our shortcode render method to pass the URL and display any message that would be returned by the callback through the $_SESSION:

So what about we build our callback method now? The callback is split in 4 other methods:

  • getToken, to ask the Facebook API to get an authentication unique token. See the Facebook documentation here for all the details.
  • getUserDetails, once we have a token, we now ask the API to get the user’s details (name, email…). You can see all the information that you can fetch here.
  • loginUser, to login the User to WordPress.
  • createUser, to register a new user in WordPress.

Therefore, to decide if we login or register the user, we save for each user a new user meta: alka_facebook_id. Which is the Facebook user’s id. If it exists in our database, we login the user. If not, we make sure registration is allowed on the site before creating a new user.

Let’s create our 4 methods within our call back method:

All good! We are ready to go.

Each method might require some comments, let me know if you have any question about them. I can update the article but the code is pretty commented though.

You can see the whole plugin from this Github repository.

Improvements

This plugin can be improved in several ways:

  • Create an option panel to get the APP ID and APP SECRET from the WordPress admin, which would be a bit more handy, right?
  • Styling our button using some cool CSS and a nice Facebook icon.
  • Displaying a welcome message when the user is logged in.
  • Saving the avatar from Facebook to WordPress.
  • Sending an email to the user with his password and username to be able to connect later without Facebook.

Liked this tutorial? Let us know, we could go through a part 2 where I would explain how to do all these improvements.

Thanks for reading!

Share

Written by

2F

Lead developer at Alkaweb.

13 Comments

  1. Hello,

    I’m new to PHP and currently using wordpress. I have been looking for a well structured clear tutorial for Facebook login until now. Thank you very much for the tut!

    Please keep part 2 coming! And if i may, will you touch on Javascript SDK and how to integrate both too?

    Many thanks!

    • By the way, how can i init the class if i don’t want it to be “plugin” ?

      • By the way, have this code been tested?

        I did this in one of my file

        But it’s showing up empty in the browser? Any help?

        • Hello,

          Yes of course, tested an used on our side 🙂

          You can call it from a theme as well but you need to make sure the file is being loaded. Using require_once for example. I would also recommend you to use this in a Child Theme so you won’t lose that change in any theme update.

          Thanks for your feedback.

          • Hello,

            It’s me again. I am getting error when using localhost. I added my localhost url to OAuth Redirect Url as stated in your guide.
            http://localhost:3000/wp-admin/admin-ajax.php?action=alka_facebook

            Any advice how to fix it?

            Below is the error:

            Can’t Load URL: The domain of this URL isn’t included in the app’s domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.

  2. Great tutorial! Its working perfectly for me… a few questions

    1) When i hit the log in button that is now on my site thanks to you, (assuming i’m already logged into Facebook) I get logged into my site without agreeing to or letting Facebook give me details to the site – is that normal? It happens automatically. I thought the user would have to “Agree” to letting Facebook give over the details?

    2) I would like to get the users ‘gender’ and ‘age range’ according to it being available through Public_Profile from Facebook.
    A) How would i do that
    B) How do i store this in WordPress? as Age and Gender is not an option>

    Again, awesome work with the above! Its great!

    B

  3. Shpend Berisha

    07 May 2017, 1:43 pm

    I did everything fine but when i clicl on the login with facebook it sends me to a blank page with a number 0 on the top left side what can be the problem?

  4. Having some trouble with step 4. I get the plugin working, with the button not doing anything, but when I try and follow the steps in number 4, I get a 500 server error.

    Any ideas why this might be happening?

    Thanks for the tutorial and looking forward to #2

  5. Firstly, I seemed to come across issues at step 4. However I have just tried to install the plugin from the Github version and I am having difficulty activating it – the following error is occuring:

    Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in /home/jellymap/public_html/wp-content/plugins/alka-facebook-master/alka-facebook.php on line 144

    Any help would be much appreciated.

    Kind regards,

    Kyle

    • Hello Kyle,

      I just checked, that’s because we are using a “new” syntax for PHP. So you need version 5.4 of PHP installed or anything above. It’s about 8 years old so some update won’t hurt. That’ll increase your site’s performance by the way.

      I hope that helps

      • Thanks man, appreciate the support – really looking forward to part 2. When do you think you’ll release it?

        Cheers,

        Kyle

        • Hi Kyle,

          Thanks for your interest. We have another tutorial coming and that’ll be the next on the list.

          Have a nice day

Leave a Reply

Your email address will not be published.Required

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

You May Also Like to Read