wp_signon()
概述
wp_signon() 函数用于验证用户凭据并登录用户,支持“记住我”功能。它设置认证 Cookie,并可在登录前后触发相关 Hook。
关键要点
- 函数接受 $credentials 数组参数,包含 user_login、user_password 和 remember 键,若未提供则从 $_POST 中获取。
- 成功时返回 WP_User 对象,失败时返回 WP_Error 对象。
- 默认情况下,$secure_cookie 参数基于 is_ssl() 自动判断,但可通过过滤器 secure_signon_cookie 自定义。
- 函数在登录前触发 wp_authenticate action,登录后触发 wp_login action。
- 注意:wp_signon() 不自动设置当前用户,若在 'init' hook 前调用,需显式调用 wp_set_current_user() 以确保 is_user_logged_in() 正确工作。
- 函数发送 HTTP 头部,必须在输出内容前调用。
代码示例
function wpdocs_custom_login() {
$creds = array(
'user_login' => 'example',
'user_password' => 'plaintextpw',
'remember' => true
);
$user = wp_signon( $creds, false );
if ( is_wp_error( $user ) ) {
echo $user->get_error_message();
}
}
add_action( 'after_setup_theme', 'wpdocs_custom_login' );注意事项
- 在 SSL 站点上,建议将 $secure_cookie 设置为 is_ssl() 以确保安全 Cookie。
- 避免在输出内容后调用此函数,否则可能导致头部已发送错误。
Authenticates and logs a user in with ‘remember’ capability.
Description
The credentials is an array that has ‘user_login’, ‘user_password’, and ‘remember’ indices. If the credentials is not given, then the log in form will be assumed and used if set.
The various authentication cookies will be set by this function and will be set for a longer period depending on if the ‘remember’ credential is set to true.
Note: wp_signon() doesn’t handle setting the current user. This means that if the function is called before the ‘init’ hook is fired, is_user_logged_in() will evaluate as false until that point. If is_user_logged_in() is needed in conjunction with wp_signon() , wp_set_current_user() should be called explicitly.
Parameters
$credentialsarrayoptional-
User info in order to sign on.
user_loginstringUsername.user_passwordstringUser password.rememberboolWhether to'remember'the user. Increases the time that the cookie will be kept. Default false.
Default:
array() $secure_cookiestring|booloptional-
Whether to use secure cookie.
Source
function wp_signon( $credentials = array(), $secure_cookie = '' ) {
global $auth_secure_cookie, $wpdb;
if ( empty( $credentials ) ) {
$credentials = array(
'user_login' => '',
'user_password' => '',
'remember' => false,
);
if ( ! empty( $_POST['log'] ) && is_string( $_POST['log'] ) ) {
$credentials['user_login'] = wp_unslash( $_POST['log'] );
}
if ( ! empty( $_POST['pwd'] ) && is_string( $_POST['pwd'] ) ) {
$credentials['user_password'] = $_POST['pwd'];
}
if ( ! empty( $_POST['rememberme'] ) ) {
$credentials['remember'] = $_POST['rememberme'];
}
}
if ( ! empty( $credentials['remember'] ) ) {
$credentials['remember'] = true;
} else {
$credentials['remember'] = false;
}
/**
* Fires before the user is authenticated.
*
* The variables passed to the callbacks are passed by reference,
* and can be modified by callback functions.
*
* @since 1.5.1
*
* @todo Decide whether to deprecate the wp_authenticate action.
*
* @param string $user_login Username (passed by reference).
* @param string $user_password User password (passed by reference).
*/
do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
if ( '' === $secure_cookie ) {
$secure_cookie = is_ssl();
}
/**
* Filters whether to use a secure sign-on cookie.
*
* @since 3.1.0
*
* @param bool $secure_cookie Whether to use a secure sign-on cookie.
* @param array $credentials {
* Array of entered sign-on data.
*
* @type string $user_login Username.
* @type string $user_password Password entered.
* @type bool $remember Whether to 'remember' the user. Increases the time
* that the cookie will be kept. Default false.
* }
*/
$secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
// XXX ugly hack to pass this to wp_authenticate_cookie().
$auth_secure_cookie = $secure_cookie;
add_filter( 'authenticate', 'wp_authenticate_cookie', 30, 3 );
$user = wp_authenticate( $credentials['user_login'], $credentials['user_password'] );
if ( is_wp_error( $user ) ) {
return $user;
}
wp_set_auth_cookie( $user->ID, $credentials['remember'], $secure_cookie );
// Clear `user_activation_key` after a successful login.
if ( ! empty( $user->user_activation_key ) ) {
$wpdb->update(
$wpdb->users,
array(
'user_activation_key' => '',
),
array( 'ID' => $user->ID )
);
$user->user_activation_key = '';
}
/**
* Fires after the user has successfully logged in.
*
* @since 1.5.0
*
* @param string $user_login Username.
* @param WP_User $user WP_User object of the logged-in user.
*/
do_action( 'wp_login', $user->user_login, $user );
return $user;
}
Hooks
- apply_filters( ‘secure_signon_cookie’, bool $secure_cookie, array $credentials )
-
Filters whether to use a secure sign-on cookie.
- do_action_ref_array( ‘wp_authenticate’, string $user_login, string $user_password )
-
Fires before the user is authenticated.
- do_action( ‘wp_login’, string $user_login, WP_User $user )
-
Fires after the user has successfully logged in.
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 4 content
Codex
This function and action can be placed in functions.php of the theme.
Using the hook after_setup_theme will make it run before the headers and cookies are sent, so it can set the needed cookie for login.
/** * Perform automatic login. */ function wpdocs_custom_login() { $creds = array( 'user_login' => 'example', 'user_password' => 'plaintextpw', 'remember' => true ); $user = wp_signon( $creds, false ); if ( is_wp_error( $user ) ) { echo $user->get_error_message(); } } // Run before the headers and cookies are sent. add_action( 'after_setup_theme', 'wpdocs_custom_login' );Skip to note 5 content
cogdog
If you want to cover your bases for SSL sites that need a secure cookie, I use (where
$credsis the array of login credentials)<br />
$autologin_user = wp_signon( $creds, is_ssl() );<br />
is_sslmethod.Skip to note 6 content
cogdog
I have some sites where in code I log in a visitor to a hidden account (to enable media uploads form front end form), admin bar is hidden, and access to dashboard is blocked. But I have a report where
wp_signon()fails and my hunch is because it is on site with SSL. I am guessing I need to use the$secure_cookieoption, but I cannot find any info on how to do this.My guess is I need to set the cookie first with
wp_set_auth_cookie()?? The option there for$securetoo is unclear.And if this is a case, do I need to test first if the host is running SSL? Will setting this cookie on an http:// site break the universe?
wp_set_auth_cookie(). However, since you’re usingwp_signon()which already sets the authentication cookie, you can pass the ‘secure’ argument directly towp_signon(), for example:$user = wp_signon( array( ..., 'secure' => is_ssl() ), false );The second argument of
wp_signon()($secure_cookie) is used to determine whether the WordPress’ default authentication actions should be run or not. By setting it tofalse, you are indicating that you don’t want the default authentication actions to run, but you still want the authentication cookie to be set. If you set it to true, the default authentication actions will run, but it will also make WordPress start a new session and overwrite any existing authentication cookie, effectively logging out the user.