Wordpress自动登录自定义页面


Wordpress auto login from custom page

在我的wordpress网站上,我创建了一个自定义注册页面,使用"PHP Code"插件在wordpress中注册。现在我想在用户完成注册后自动登录。我做了很多研究,但找不到解决问题的方法。我尝试在自定义页面中测试以下示例代码片段:

<?php
//Log in a WordPress user programmatically
function auto_login( $user ) {
    $username   = $user;
    if ( !is_user_logged_in() ) {
        $user = get_user_by('login', $username );
        $user_id = $user->ID;
        wp_set_current_user( $user_id, $user_login );
        wp_set_auth_cookie( $user_id );
        do_action( 'wp_login', $user_login );
    }     
}
auto_login('admin');
?>

但我得到以下错误。

Warning: Cannot modify header information - headers already sent by (output started at /home/content/19/11054119/html/wp-content/plugins/sitepress-multilingual-cms/inc/language-switcher.php:921) in /home/content/19/11054119/html/wp-includes/pluggable.php on line 925
Warning: Cannot modify header information - headers already sent by (output started at /home/content/19/11054119/html/wp-content/plugins/sitepress-multilingual-cms/inc/language-switcher.php:921) in /home/content/19/11054119/html/wp-includes/pluggable.php on line 926
Warning: Cannot modify header information - headers already sent by (output started at /home/content/19/11054119/html/wp-content/plugins/sitepress-multilingual-cms/inc/language-switcher.php:921) in /home/content/19/11054119/html/wp-includes/pluggable.php on line 927

所以我想知道无论如何要做自动登录而不触及主题功能。如果你有任何想法或解决方案,请帮助我。

谢谢

您应该使用核心函数wp_signon https://codex.wordpress.org/Function_Reference/wp_signon这是示例代码

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

您可以这样尝试:

   if( isset($_POST['log']) && isset($_POST['pwd']) ):
      $creds = array( 'user_login' =>  $_POST['log'], 'user_password' => $_POST['pwd'], 'remember' => $_POST['rememberme'] );
      $user = wp_signon( $creds, false );
      if ( is_wp_error($user) ): echo $user->get_error_message(); endif;
      wp_set_current_user($user->ID);
      return $user;
    endif;

你可以在这里查看更多信息

 //Log in a WordPress user programmatically
        function auto_login( $username ) {            
            if ( !is_user_logged_in() ) {
                $UserData = get_user_by('login', $username );
                $iUserid = $UserData->ID;
                $UserLogin = $UserData->user_login;
                wp_set_current_user($iUserid, $UserLogin);
                wp_set_auth_cookie($iUserid);
                do_action('wp_login', $UserLogin);
            }     
        }
        auto_login('admin');