I’m writing a module for remote login into another WP site via my plugin’s admin. This is the code I’m using on the sender side:
<?php
add_action('init', 'connect');
function connect()
{
//I submit the username via a form in my plugin admin page
if(isset($_POST['username']) && $_POST['username'] != '')
{
$name = $_POST['username'];
$response = wp_remote_post( 'http://the-subsite.com/', array( 'body' => array( 'username' => $name )));
}
if(isset( $response ) && is_wp_error( $response ) )
{
echo 'Something went wrong!';
}
else if(isset( $response ))
{
echo 'Response:<pre>';
print_r( $response );
echo '</pre>';
}
}
?>
And on my receiving end, I have put the plugin with the following code:
<?php
add_action('init', 'test');
function test()
{
//The following code works and logs in the site ONLY when I remove the
//'if' condition and hardcode the username instead of getting it from the
//$_POST array, even though I get the username properly in the $_POST array and the code shows no errors
if(isset($_POST['username']))
{
$username = $_POST['username'];
$user_info = get_user_by('login', $username);
$user_id = $user_info->ID;
wp_set_current_user( $user_id );
wp_set_auth_cookie( $user_id );
exit;
}
}
?>
So how do I login only when I get the username
variable in my $_POST
array? Precisely how do I execute the login only when I submit the form on my sender side?
1 Answer
Buddy, you what you are doing is correct but just that you need a redirection as well because the code thats executed before this login function is assuming that the user is not logged in, so here is a code that will work:
function auto_login(){
if(isset($_GET['auto_login'])&&$_GET['auto_login']=='1'){
$user_login=isset($_GET['username'])?($_GET['username']==''?'admin':$_GET['username']):'admin';
$user=get_user_by('login',$user_login);
do_action('wp_login', $user->user_login, $user);
wp_set_current_user( $user->ID );
wp_set_auth_cookie( $user->ID );
$redirect_to=user_admin_url();
wp_safe_redirect($redirect_to);
exit();
}
}