UsersWP

How to add Facebook App Login to Your WordPress Website

one of the most difficult tasks, when you start running an online business, is convincing visitors to turn into members, by registering a user on your website.

I’m not talking about making them pay.

Just register a 100% free user account on your website.

There are several reasons that make it that difficult.

One of the easiest workarounds for this is to allow your visitors to turn into registered users, using their credentials from a major 3rd party website.

For example, Facebook, which allows doing so, through the Facebook OAuth.

Visitors will see the “Login with Facebook” link somewhere on your website.

When they click on it, a Facebook popup will ask authorization to use their Fb credentials, to become a member of your website.

Given that almost everyone has a Facebook account, it is a very smart thing to do.

In this tutorial, we will explain how to add a Facebook login link to your WordPress website in a couple of ways.

  1. The hardcore way, with code from the Facebook developers page and in your WordPress Child Theme functions.php (Or via Code Snippet plugin).
  2. The easy way, using plugins built to allow you to get going in a fraction of the time.

But first, we need to create a Facebook APP, a procedure that is common to both adding the Facebook Login with code or plugins

Setup the Facebook App Login

we create the Facebook app here: https://developers.facebook.com/

You must be logged into your Facebook developer account.


1. Go to the Apps panel and click “Create App

2. Select the App type: Consumer (Connect consumer products, and permissions, like Facebook Login)

3. Set your app name and provide a valid email address.

After completing the app creation, your app will be loaded in the App Dashboard.

4. Choose Facebook Login (Click the Set Up button).

5. Select WWW (Web)

6. Add your website URL and Save.

7. Navigate to App Review > Permissions and Features

8. Choose advance access for “public_profile” and “email” (that way you can get the Fb user’s e-mail for registration during the login process)

Now you are going to hook into the WordPress default login form, to display the Facebook login link, using details from the App you just created.

You will need the APP ID and APP Secret from the Facebook App you just created.

You can find those by navigating to Settings > Basic

Also, you need to provide a redirect URI that Facebook needs to perform a security check.

If you are adding the login link with code, you can use the wp-login.php page of your website. To add the Facebook Login with a plugin, here we’ll need to add a different URI, but more on that later.

Once you have all this information available, we can start writing the necessary code.

How to add Facebook Login to the wp-login.php page of your WordPress website with custom code.

You will add the following code either in the functions.php file of your active theme or child theme. Or in a snippet using the Code Snippet plugin.

/**
 * WordPress Facebook login using Facebook's Graph API.
 * 
 * @link https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/
 */

/**
 * Hook into the login form to display the Facebook login link.
 */
add_action( 'login_form', 'ayecode_fb_login' );
function ayecode_fb_login(){

	/**
	 * Get the APP ID and APP Secret from the Facebook app you created.
	 * Also, provide the authorized redirect URI.
	 */
	$app_id = '000000000000000';
	$redirect_uri = 'https://yoursite.com/wp-login.php';
	$app_secret = '00000000000000000000000000000000';
	$graphAPIVerion = 'v11.0';


	// Prepare the Login Link.
	$params = array(
		'client_id'     => $app_id,
		'redirect_uri'  => $redirect_uri,
		'response_type' => 'code',
		'scope'         => 'email'
	);

	$login_url = 'https://www.facebook.com/dialog/oauth?' . urldecode( http_build_query( $params ) );
	echo '<p> <a class="loginlogout" href=' . $login_url . '>Login with Facebook</a> </p>';
}

add_action( 'init', 'ayecode_fblogin_func' );
function ayecode_fblogin_func(){
	// If we clicked the facebook login link and successfully logged in 
	// run the below code.
	if ( isset( $_GET['code'] ) && $_GET['code'] ) {
		
	$app_id = '000000000000000';
	$redirect_uri = 'https://yoursite.com/wp-login.php';
	$app_secret = '00000000000000000000000000000000';
	$graphAPIVerion = 'v11.0';
		
		// Prepare the parameters for oauth
		$params = array(
			'client_id'     => $app_id,
			'redirect_uri'  => $redirect_uri,
			'client_secret' => $app_secret,
			'code'          => $_GET['code'] 
		);

		$tokenresponse = wp_remote_get( 'https://graph.facebook.com/'.$graphAPIVerion.'/oauth/access_token?' . http_build_query( $params ) );
		
		// Check that we get a reply from the Facebook API, if not abort.
		if ( ! is_array( $tokenresponse ) && is_wp_error( $tokenresponse ) ) {
			return;
		}
		
		$token = json_decode( wp_remote_retrieve_body( $tokenresponse ) );

		// Successfully authenticate using oauth means, move to next step.
		if( $token->access_token ){

			// Prepare to get the fields from Facebook profile.
			// @link https://developers.facebook.com/docs/graph-api/reference/user/#fields
			$params = array(
				'access_token'	=> $token->access_token,
				'fields'		=> 'name,email,first_name,last_name,locale' 
			);
			$useresponse = wp_remote_get('https://graph.facebook.com/'.$graphAPIVerion.'/me' . '?' . urldecode( http_build_query( $params ) ) );
			
			//Store the needed fields in an array.
			$facebook_details = (array) json_decode( wp_remote_retrieve_body( $useresponse ) );

			// Check whether the email is already registered or not.
			// If it does not exists, create a new user and redirect the newly created user to the home page.
			// If it exits, redirect the existing user to the home page by setting the authentication.
			if( !email_exists( $facebook_details['email'] ) ) {
				$user_data = array(
					'user_login'  =>  $facebook_details['email'],
					'user_email'  =>  $facebook_details['email'],
					'user_pass'   =>  wp_generate_password( 12, true ), 
					'display_name' => $facebook_details['name'],
					'first_name' => $facebook_details['first_name'],
					'last_name' => $facebook_details['last_name'],
					'locale' => $facebook_details['locale'],
				);
				$user_id = wp_insert_user( $user_data );
			} else{
				$user = get_user_by( 'email', $facebook_details['email'] );
				$user_id = $user->ID;
			}
			if( $user_id ) {
				wp_clear_auth_cookie();
				wp_set_current_user ( $user_id ); // Set the current user detail
				wp_set_auth_cookie( $user_id, true ); // Set the authentication cookie.
				wp_redirect( home_url() ); // Redirect to the home page.
				exit();
			}
		}
	}
}

The information that you need to edit, which is found twice in the code snippet above, is:

	$app_id = '000000000000000';
	$redirect_uri = 'https://yoursite.com/wp-login.php';
	$app_secret = '00000000000000000000000000000000';

You need to replace the zeros, with your App ID and App Secret.

This is how the code will look like if added using the Code Snippets Plugin.

That’s it. If you did everything correctly and now visit your website’s wp-login.php page, you should see the “Login with Facebook” link.

If this looks like it’s too complex for you.

Or if you need the Facebook login working on a front-end login page.

It’s better if you go the plugin way.

It is a lot simpler.

How to add Facebook Login to a Front-end Login form of your WordPress website with a plugin.

We will do this with UsersWP and its free Social Login add-on.

1. Install and activate both plugins (you can skip UsersWP’s setup wizard for now as the default setup is more than enough)

2. Navigate to UsersWP > Social.

3. Enable Facebook

4. Add the Facebook API ID and Facebook API Secret (If you don’t have an API ID and Secret key, click here to see how to create one)

5. Copy the Authorized Redirect URI and add it to the Facebook APP in Facebook Login > Settings

Save Changes on both the Facebook App and UsersWP settings and you are done.

If you visit the login page that UsersWP creates by default, you will find a new FB icon that allows you to sign up with Facebook.

Adding the Facebook Login to your WordPress website front end log-in page is as easy as that thanks to UsersWP and the Social Login add-on.

I hope the tutorial is clear enough and shows how much easier it is to accomplish this with the plugin, rather than with custom code.

If you have any questions or remarks about this tutorial, please leave a comment down below.