仅使用用户名不起作用的远程登录

时间:2012-02-27 作者:Rutwick Gangurde

我正在编写一个模块,通过插件的管理员远程登录到另一个WP站点。这是我在发送方使用的代码:

<?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>\';
    }
}
?>
在我的接收端,我将插件与以下代码放在一起:

<?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;
    }
}
?>
那么,只有当我获得username 我生活中的变数$_POST 大堆确切地说,只有在发件人端提交表单时,我如何执行登录?

1 个回复
最合适的回答,由SO网友:Gagan 整理而成

伙计,你所做的是正确的,但你也需要重定向,因为在此登录功能之前执行的代码假设用户未登录,因此下面是一个可以工作的代码:

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();
}
}

结束

相关推荐