Answers:
wp_set_auth_cookie()
无需知道密码即可登录用户。
is_user_logged_in()
似乎不起作用。您知道它在寻找与Cookies不同的东西吗?
wp_set_current_user
在登录之前。
wp_set_auth_cookie()
了我的登录功能。我想我需要重新考虑一下。我还将查找wp_set_current_user并进行报告。非常感谢您的帮助!
以下代码无需任何密码即可完成自动登录的工作!
// Automatic login //
$username = "Admin";
$user = get_user_by('login', $username );
// Redirect URL //
if ( !is_wp_error( $user ) )
{
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
$redirect_to = user_admin_url();
wp_safe_redirect( $redirect_to );
exit();
}
get_user_by()
失败时返回false,因此您应该检查false而不是WP_Error对象
我在这里找到了另一个使用更好方法的解决方案(至少在我看来...)。无需设置任何cookie,它使用Wordpress API:
/**
* Programmatically logs a user in
*
* @param string $username
* @return bool True if the login was successful; false if it wasn't
*/
function programmatic_login( $username ) {
if ( is_user_logged_in() ) {
wp_logout();
}
add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 ); // hook in earlier than other callbacks to short-circuit them
$user = wp_signon( array( 'user_login' => $username ) );
remove_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );
if ( is_a( $user, 'WP_User' ) ) {
wp_set_current_user( $user->ID, $user->user_login );
if ( is_user_logged_in() ) {
return true;
}
}
return false;
}
/**
* An 'authenticate' filter callback that authenticates the user using only the username.
*
* To avoid potential security vulnerabilities, this should only be used in the context of a programmatic login,
* and unhooked immediately after it fires.
*
* @param WP_User $user
* @param string $username
* @param string $password
* @return bool|WP_User a WP_User object if the username matched an existing user, or false if it didn't
*/
function allow_programmatic_login( $user, $username, $password ) {
return get_user_by( 'login', $username );
}
我认为代码是不言自明的:
过滤器搜索给定用户名的WP_User对象并返回它。wp_set_current_user
用WP_User对象返回的函数调用wp_signon
检查以is_user_logged_in
确保您已登录,仅此而已!
我认为这是一段不错的干净代码!
$credentials
为空。如果数组不为空(我的回答就是这种情况),则使用数组中的值对用户进行身份验证。
除了Mike,Paul和Sjoerd:
为了更好地处理login.php
重定向:
//---------------------Automatic login--------------------
if(!is_user_logged_in()){
$username = "user1";
if($user=get_user_by('login',$username)){
clean_user_cache($user->ID);
wp_clear_auth_cookie();
wp_set_current_user( $user->ID );
wp_set_auth_cookie( $user->ID , true, false);
update_user_caches($user);
if(is_user_logged_in()){
$redirect_to = user_admin_url();
wp_safe_redirect( $redirect_to );
exit;
}
}
}
elseif('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] == wp_login_url()){
$redirect_to = user_admin_url();
wp_safe_redirect( $redirect_to );
exit;
}
放在wp-config.php
之后
require_once(ABSPATH . 'wp-settings.php');
费耶
基于上述解决方案,我发布了一个插件,通过同步用户数据和cookie会话来保持用户从一个wordpress登录到另一个wordpress: