Here we are discussing a scenario where we have two wordpress websites with two different databases running at different domains or sub-domains. We are explaining a feature like SSO (Single Sign On) for wordpress websites.
autologin

Our motive is to implement the functionality where a user comes to our first website and and clicks a link to go to his second website, he will find himself logged in there. In this case, user do not require to login for his second website. We are also handling few situations here :

  1. If the user already registered in our second website then he will be logged in there having all the user capabilities of that user in second website.
  2. If the user not already registered in our second website, then it registers with details according to our first website and then logged in. New user registration takes place with his username as password and role as subscriber.
  3. Basically we are matching emails between both the websites. As we know that wordpress does not allow user registration from same email more than one time.

In this tutorial we are using wordpress default functions to maintain the wordpress flow. Now, just take an example to make it more clear, we have two websites like :

  • First Website : http://firstwebsite.com
  • Second Website : http://secondwebsite.com

Now, first of all create a link on your first website, on which we want to click to go to our second website as a logged in user. So, in your first website create a link at your desired place as mentioned below :

<?php   global $current_user;
                                $second_website_url = 'http://secondwebsite.com'; // put your second website url
                                $user_email = $current_user->user_email;
                                $user_login = $current_user->user_login;
                                if($user_email != ''){

                                    $email_encoded = rtrim(strtr(base64_encode($user_email), '+/', '-_'), '='); //email encryption
                                    $user_login_encoded = rtrim(strtr(base64_encode($user_login), '+/', '-_'), '='); //username encryption
                                    echo '<a href="'.$second_website_url.'/sso.php?key='.$email_encoded.'&detail='.$user_login_encoded.'" target="_blank">Link to second website</a>';

                        }?> 

Look at the above code, it is sending our current user email and username in encrypted format to make them secure.

Now, open our second website and create a new php file and name it as “sso.php”. Place this file at your root installation and just copy paste the below mentioned code in this file :

<?php

require_once( 'wp-load.php' ); //put correct absolute path for this file


global $wpdb;

if(isset($_GET['key']) && !empty($_GET['key'])){

    $email_decoded = base64_decode(strtr($_GET['key'], '-_', '+/'));  // decrypt email 
    $username_decoded = base64_decode(strtr($_GET['detail'], '-_', '+/')); // decrypt username

    $received_email = sanitize_text_field($email_decoded);
    $received_username = sanitize_text_field($username_decoded);


    if( email_exists( $received_email )) {

            //get the user id for the user record exists for received email from database 
            $user_id = $wpdb->get_var($wpdb->prepare("SELECT * FROM ".$wpdb->users." WHERE user_email = %s", $received_email ) );

            wp_set_auth_cookie( $user_id); //login the previously exist user

            wp_redirect(site_url()); // put the url where you want to redirect user after logged in

    }else {

            //register those user whose mail id does not exists in database 

            if(username_exists( $received_username )){

                //if username coming from first site exists in our database for any other user,
                //then the email id will be set as username
                $userdata = array(
                'user_login'  =>  $received_email,
                'user_email'  =>  $received_email, 
                'user_pass'   =>  $received_username,   // password will be username always
                'first_name'  =>  $received_username,  // first name will be username
                'role'        =>  'subscriber'     //register the user with subscriber role only
            );

            }else {

                $userdata = array(
                'user_login'  =>  $received_username,
                'user_email'  =>  $received_email, 
                'user_pass'   =>  $received_username,   // password will be username always
                'first_name'  =>  $received_username,  // first name will be username
                'role'        =>  'subscriber'     //register the user with subscriber role only
            );

            }


            $user_id = wp_insert_user( $userdata ) ; // adding user to the database

            //On success
            if ( ! is_wp_error( $user_id ) ) {
                
                wp_set_auth_cookie( $user_id); //login that newly created user
                wp_redirect(site_url()); // put the url where you want to redirect user after logged in

            }else{

                echo "There may be a mismatch of email/username with the existing record.
                      Check the users with your current email/username or try with any other account.";die;
            }


    }

     die;

} ?>

Now you are done with your code, let us check few points which are describing the limitations, inclusions and considerations of the above code :

  • Link on first website is only visible when a user logged in there.
  • It is required to login on first website to go to second website as logged in already
  • Sending email and username in encrypted format from first site to another
  • If email exists in database of second site then user will login as per existing details
  • If email not found in database then user registration takes place in second website, with role as “subscriber” and username & email as received from first website.
  • Password for newly registered user will be same as username initially, you can change it.
  • After registration, the new user will logged in to second site automatically.

The above mentioned functionality includes simple cases and uses default wordpress functions. You can modify the code as per your requirement.
Comment here if you face any issue regarding this code or contact me to solve problems associated to your wordpress websites.
You can also contact me to build a new wordpress website for you.

Happy coding 🙂