問題描述
我以程式設計方式手動建立使用者,我想登入新建立的使用者。 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。