以编程方式登录WordPress用户

时间:2014-07-17 作者:user54952

我正在尝试以编程方式登录wordpress用户,使用以下函数进行登录。

    public function auto_login( $user ) {
        $username = $user;
            if ( !is_user_logged_in() ) {
            $user = get_user_by( \'login\', $username );
                wp_set_current_user( $user->ID, $user->user_login );
                wp_set_auth_cookie( $user->ID );
                do_action( \'wp_login\', $user->user_login );
            }     
}
不幸的是,它似乎不起作用。该函数是从短代码中调用的。这就是原因吗?在输出任何内容之前,我是否应该将函数挂接到某个过滤器上?另外,我想根据$\\u GET参数将新登录的用户重定向到特定的帖子,我可以简单地在函数末尾添加标题重定向吗?

提前感谢您的帮助!

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

在template\\u重定向挂钩上执行此操作。您可以使用wp\\u safe\\u redirect重定向到博客中的不同页面。我不能给你代码,因为我不知道你从哪里得到$用户

SO网友:TBI Infotech

您可以尝试此功能,因为它对我有效

function custom_login() {
    $creds = array();
    $creds[\'user_login\'] = \'example\';
    $creds[\'user_password\'] = \'plaintextpw\';
    $creds[\'remember\'] = true;
    $user = wp_signon( $creds, false );
    if ( is_wp_error($user) )
        echo $user->get_error_message();
}
// run it before the headers and cookies are sent
add_action( \'after_setup_theme\', \'custom_login\' );
有关详细信息,请访问official site 在这里

结束