Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8950209
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T13:24:10+00:00 2026-06-15T13:24:10+00:00

I am building a user generated content sharing theme and I want to make

  • 0

I am building a user generated content sharing theme and I want to make a custom Facebook connect. After researching, I found out this code.

The following code is adding the app to the users profile in Facebook, but is not creating a new user and also doesn’t makes them logged in.

Here is the full code (to be added in functions.php).

Step 1 – Intializing javascript at header area

function fb_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', 'fb_head' );

Step 2 – Inserting a button for facebook login

<button id="facebook_connect">Connect with facebook</button>

Step 3 – Loading Jquery Library

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

Step 4 – Add a jQuery on-click function to the button we have created

This code will be placed on the wp footer section (before the closing body tag).

function fb_footer(){
    if( is_user_logged_in()):
        echo "<script type='text/javascript'> jQuery('#facebook_connect').hide(); </script>";
        return;
    endif;
    ?>
    <script type="text/javascript">
        jQuery('#facebook_connect').click(function(){
            FB.login(function(FB_response){
                if( FB_response.status === 'connected' ){
                    fb_intialize(FB_response);
                }
            },
            {scope: 'email'});
        });

        function fb_intialize(FB_response){
            FB.api( 
                '/me', 
                'GET', 
                {'fields':'id,email,username,verified,name'},
                function(FB_userdata){
                    jQuery.ajax({
                        type: 'POST',
                        url: 'AJAXURL',
                        data: {
                            "action": "fb_intialize", 
                            "FB_userdata": FB_userdata, 
                            "FB_response": FB_response
                        },
                        success: function(user){
                            if( user.error ){
                                alert( user.error );
                            }
                            else if( user.loggedin ){
                                window.location.reload();
                            }
                        }
                    });
                }
            );
        };
    </script>
    <?php
}
add_action( 'wp_footer', 'fb_footer' );

Step 5 – MAIN STEP: Adding the handler function

function wp_ajax_fb_intialize(){
    @error_reporting( 0 ); // Don't break the JSON result
    header( 'Content-type: application/json' );

    if( !isset( $_REQUEST['FB_response'] ) || !isset( $_REQUEST['FB_userdata'] ))
        die( json_encode( array( 'error' => 'Authonication required.' )));

    $FB_response = $_REQUEST['FB_response'];
    $FB_userdata = $_REQUEST['FB_userdata'];
    $FB_userid = (int) $FB_userdata['id'];

    if( !$FB_userid )
        die( json_encode( array( 'error' => 'Please 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 ( !get_option( 'users_can_register' ))
                die( json_encode( array( 'error' => 'Registration is not open at this time. Please come back later..' )));

            extract( $FB_userdata );

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

            if( empty( $verified ) || !$verified )
                die( json_encode( array( 'error' => 'Your facebook account is not verified. You hae to verify your account   before proceed login or registering on this site.' )));

            $user_email = $email;
            if ( empty( $user_email ))
                die( json_encode( array( 'error' => 'Please re-connect your facebook account as we couldnt find your email  address..' )));

            if( empty( $name ))
                die( json_encode( array( 'error' => 'empty_name', 'We didnt find your name. Please complete your facebook   account before proceeding..' )));

            if( empty( $user_login ))
                $user_login = sanitize_title_with_dashes( sanitize_user( $display_name, true ));

            if ( username_exists( $user_login ))
                $user_login = $user_login. time();

            $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 ))
                die( json_encode( array( 'error' => $user_ID->get_error_message())));

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

    wp_set_auth_cookie( $user_ID, false, false );
    die( json_encode( array( 'loggedin' => true )));
}
add_action( 'wp_ajax_nopriv_fb_intialize', 'wp_ajax_fb_intialize' );

THis is how I add the Facebook button:

 <button id="facebook_connect">Connect with Facebook</button>

If anyone is trying it please replace the App ID.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T13:24:11+00:00Added an answer on June 15, 2026 at 1:24 pm

    Changed the ajax url from

    url: 'AJAXURL',
    

    to

    url: '<?php echo admin_url('admin-ajax.php'); ?>',
    

    One thing I noticed while testing was that if I delete a user from the wp_users table the user meta with the facebook id will still be there so you may need to check if the facebook id is associated with an invalid user id in your ajax callback e.g.

    global $wpdb;
    $user_ID = $wpdb->get_var( "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '_fbid' AND meta_value =  '$FB_userid'" );
    
    // check if the user id is valid
    if( false === ($check_user = get_userdata($user_ID)) )
    {
      $user_ID = false; // set to false to force create a new user
    }
    

    The rest of your code worked fine.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm building a website with user generated content. On the home page I want
I'm currently building a user control that displays a message when a Repeater is
I am currently building a user admin area for my site that would require
I'm working on a CakePHP project and am currently building the user authentication part
I am building my first user control and I would like to package the
Hi all im building a web user interface. In this interface i use popup
So I have this calculator I'm building that accepts user variable inputs like let
I am building a social networking site with user, school, and schoolgroup models. The
I am building an application where the user can save some information into an
I'm building a website that will require user registration and logon. I would like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.