试试这个完整的代码它工作 100% 第一个网站: http: //firstwebsite.com和第二个网站:http ://secondwebsite.com
现在,首先在您的第一个网站上创建一个链接,我们要单击该链接以作为登录用户访问我们的第二个网站。因此,在您的第一个网站中,在您想要的位置创建一个链接,如下所述:
<?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), '+/', '-_'), '=');
$user_login_encoded = rtrim(strtr(base64_encode($user_login), '+/', '-_'), '=');
echo '<a href="'.$second_website_url.'/sso.php?
key='.$email_encoded.'&detail='.$user_login_encoded.'" target="_blank">Link to
second website</a>';
}?>
现在,打开我们的第二个网站并创建一个新的 php 文件并将其命名为“sso.php”。将此文件放在您的根安装中,然后将下面提到的代码复制粘贴到此文件中:
<?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'], '-_', '+/'));
$username_decoded = base64_decode(strtr($_GET['detail'], '-_', '+/'));
$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;
} ?>