問題描述
我以編程方式手動創建用户,我想登錄新創建的用户。 WP 可以輕鬆訪問散列密碼,而不是明文版本。有沒有明文密碼使用 wp_signon() 的方法?
我發現一個人聲稱已經做了這個 here,但是對我來説並不奏效。
謝謝!
最佳解決方案
wp_set_auth_cookie()將登錄用户而不必知道他們的密碼。
次佳解決方案
以下代碼可以自動登錄,沒有任何密碼!
// 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();
}
第三種解決方案
我已經找到了另一種解決方案 here,使用更好的方法 (至少在我看來…) 。不需要設置任何 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_signon 返回的 WP_User 對象調用函數 wp_set_current_user,使用函數 is_user_logged_in 檢查以確保您已登錄,就這樣!
在我看來,一個漂亮乾淨的代碼!
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。