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?
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:
}