Integrate Registration with Facebook Account on WordPress Site

If you want to build Registration with Facebook Account without using any plugin, this article will help you to do so. All of the codes can be placed on your themes functions.php file, or any file included through that file, or within an active plugin.


Step 1: Register Facebook Application

Register a facebook application and grab the application id. If you are not sure how to do this, Google how to register a facebook application and then visit Facebook application page to register your application.


Step 2: Load Facebook JavaScript SDK

Next, initialize Facebook JavaScript on your WP Site header area. Add the following code. Replace APP_ID with your Facebook application ID/API key.

function FbC_head() {
    if ( is_user_logged_in() ) {
        return;
    }
    ?>
    <script type="text/javascript">
    window.fbAsyncInit = function(){
        FB.init({appId:'APP_ID', status:true, cookie:true, xfbml:true, oauth:true});
    };
    </script>

    <div id="fb-root"></div>

    <script type="text/javascript">
    (function() {
    var e = document.createElement('script');
    e.type = 'text/javascript';
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
    }());
    </script>
    <?php
}
add_action( 'wp_head', 'FbC_head' );

This will be place on head, if the user is not logged in.


Step 3: Insert the button

At this point, insert a button or anchor link to your site and give it a unique CSS id. You can insert it on a widget, or within a page or post content or within your theme template file.

<button id="FbConnect">Connect with facebook</button>
Or
<a id="FbConnect" href="#">Connect with facebook</a>

You can stylize the button as you want with CSS to give it a Facebook button look.


Step 4: Loading jQuery

jQuery library is required to be loaded on the page. It can be safely loaded with the following code –

function FbC_enqueue_scripts(){
    wp_enqueue_script( 'jquery' );
}
add_action( 'wp_enqueue_scripts', 'FbC_enqueue_scripts' );

Step 5: Setting up a click event handler for the button

After clicking on the button a popup will appear and Facebook will ask the user to authorize your application (if it hasn’t been yet). If the user cancel the authorization, the poup will close and nothing will happen. But, if he Authorize the application, then we will grab his/her information using Facebook Graph API. Next, we will check if the user already register earlier with the Facebook account, if a match found, we will log him in, else we will create a new account and make the user loging to the site.

This code will try to connect the user with your Facebook application, grab a token, and send it to our validator using Ajax.

function FbC_footer() {
	if ( is_user_logged_in() ) :
		// hiding the button for loggedin user using jQuery.
		echo "<script type='text/javascript'>jQuery('#FbConnect').hide(); </script>";
		return;
	endif;
	?>
	<script type="text/javascript">
	jQuery(document).ready(function(){
		jQuery('#FbConnect').click(FbConnect);
	});

	function FbConnect(){
		FB.login(function(response){
			if ( response.status === 'connected' ){
				jQuery.post( '<?php admin_url('admin-ajax.php'); ?>', {"action": "FbConnect", "FbToken": response.authResponse.accessToken}, function(r){
					if ( ! r.success ){
						alert( r.data.error );
					} else {
						window.location.reload();
					}
				});
			}
			else{
				alert('You are not connected');
			}
		},
		{scope: 'email'});
	}
	</script>
	<?php
}
add_action( 'wp_footer', 'FbC_footer' );

Step 5: Adding the Ajax request handler

The following code should go inside the functions.php file.

function FbConnect_ajax() {
	// check if the token has passed
	if ( empty( $_REQUEST['FbToken'] ) ) {
		wp_send_json_error( array( 'error' => 'Authentication required.' ));
	}

	$FbToken = $_REQUEST['FbToken'];
	$url = "https://graph.facebook.com/me?fields=id,email,username,verified,name&access_token=$FbToken";

	// get the userdata using the token
	$body = wp_remote_retrieve_body( wp_remote_request( $url, array( 'timeout' => '30', 'sslverify' => false ) ) );
	if ( is_wp_error($body) || empty( $body )) {
		wp_send_json_error( array( 'error' => 'Unable to retrieve data.' ));
	}

	$FB_userdata = json_decode( $body );
	if ( is_object( $FB_userdata )) {
		$FB_userdata = get_object_vars( $FB_userdata );
	}

	$FB_userid = (int) $FB_userdata['id'];
	if ( ! $FB_userid ){
		wp_send_json_error( array( 'error' => 'Please Re-connect your facebook account.' ));
	}

	global $wpdb;
	$user_ID = $wpdb->get_var( "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '_fbid' AND meta_value = '$FB_userid'" );

	if ( ! $user_ID ) {
		$user_email = $FB_userdata['email'];
		$user_ID = $wpdb->get_var( "SELECT ID FROM $wpdb->users WHERE user_email = '$user_email'" );

		if( ! $user_ID ) {
			// if registration is disabled from General Settings page, not necessary to register a new account
			if ( ! get_option( 'users_can_register' )) {
				wp_send_json_error( array( 'error' => 'Registration is not open at this time. Please come back later..' ));
			}

			extract( $FB_userdata );

			$display_name = $name;
			$user_login = $username;

			// checks if the facebook account is verified
			if ( empty( $verified ) || !$verified ) {
				wp_send_json_error( array( 'error' => 'Your facebook account is un-verified. You have to verify your facebook account before proceed..' ));
			}

			$user_email = $email;
			if ( empty( $user_email )){
				wp_send_json_error( array( 'error' => 'Please re-connect your facebook account. [EMAIL NOT FOUND]' ));
			}

			if ( empty( $display_name )) {
				wp_send_json_error( array( 'error' => 'We didn\'t find your name from facebook. Please complete your facebook account before proceeding..' ));
			}

			// if username empty, try to create from name
			if ( empty( $user_login )) {
				$user_login = sanitize_title_with_dashes( sanitize_user( $display_name, true ));
			}

			$user_login_check = $wpdb->get_var( "SELECT user_login FROM $wpdb->users WHERE user_login = '$user_login' LIMIT 1" );

			// find an available username
			if ( $user_login_check ) {
				$suffix = 2;
				do {
					$alt_user_login = $user_login . "-$suffix";
					$user_login_check = $wpdb->get_var( "SELECT user_login FROM $wpdb->users WHERE user_login = '$alt_user_login' LIMIT 1" );
					$suffix++;
				} while ( $user_login_check );
					$user_login = $alt_user_login;
				}

				$user_login = esc_sql( $user_login );
				$user_pass = wp_generate_password( 12, false );

				$userdata = compact( 'user_login', 'user_email', 'user_pass', 'display_name' );

				$user_ID = wp_insert_user( $userdata );
				if ( is_wp_error( $user_ID )) {
					wp_send_json_error( array( 'error' => 'Unable to register, please try again.' ));
				}

				update_user_meta( $user_ID, '_fbid', (int) $id );
			} else {
				update_user_meta( $user_ID, '_fbid', (int) $FB_userdata['id'] );
			}
		}

		$userdata = new WP_User( $user_ID );
		if ( ! $userdata ) {
			wp_send_json_error( array( 'error' => 'Something went wrong, your account not found. Please try again or contact support' ));
		}
	}

	$userdata = $userdata->data;

	// Let Other hook to the login user information. If they restrict a user for some reason, we will also do that.
	$userdata = apply_filters( 'wp_authenticate_user', $userdata );
	if ( is_wp_error( $userdata )) {
		wp_send_json_error( array( 'error' => $userdata->get_error_message() ) );
	}

	wp_set_auth_cookie( $user_ID, false, false );
	do_action( 'wp_login', $userdata->user_login, $userdata );

	wp_send_json_success( array( 'loggedin' => true ) );
}

add_action( 'wp_ajax_nopriv_FbConnect', 'FbConnect_ajax' );

With the wp_ajax_FbConnect’ function, we are checking –

  • – Firstly, we validate the user token and try to fetch his facebook data that we need to create an account.
  • – Secondly, do we already have current facebook user id on our WordPress user meta table, if we found one, we will set login cookie for that user.
  • – Thirdly, do we already have a WP user register with the current facebook users primary email, if we found one, we will set login cookie for that user.
  • If these last two method fails, we will mark the current user as an unregistered user and will register him.

Any errors will be displayed using JavaScript alert function.

If you have placed everything properly, now you have a working Registration with Facebook Account Script for your site.