wp_signon()
Authenticates and logs a user in with 'remember' capability.
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.
Hooks from the function
Return
WP_User|WP_Error
. WP_User on success, WP_Error on failure.
Usage
wp_signon( $credentials, $secure_cookie );
- $credentials(array)
User info in order to sign on.
Default: array()
-
user_login(string)
Username. -
user_password(string)
User password. - remember(true|false)
Whether to 'remember' the user. Increases the time that the cookie will be kept.
Default: false
-
- $secure_cookie(string|true|false)
- Whether to use secure cookie.
Default: ''
Examples
#1 An example of the authorization of the user Leonid:
$creds = []; $creds['user_login'] = 'Leonid'; $creds['user_password'] = 'password'; $creds['remember'] = true; $user = wp_signon( $creds, false ); if ( is_wp_error( $user ) ) { echo $user->get_error_message(); }
NOTE: This code must be run before the headers and cookies are sent.
#2 Example of authorization, through the $_POST
data.
To do this pass to $_POST the following data and the function make authorization itself: "log", "pwd" and "rememberme":
// Suppose we already have the following variables defined: // $_POST['log'], $_POST['pwd'], $_POST['rememberme'] // then the authorization will go as follows $user = wp_signon(); if ( is_wp_error( $user ) ) { echo $user->get_error_message(); }
#3 WP Sign on for SSL sites
WP Sign on for SSL sites that need a secure cookie, I use (where $creds i)
// $creds - s the array of login credentials $autologin_user = wp_signon( $creds, is_ssl() );
If you’re not explicitly setting the usage of secure cookies, not passing a second argument will default to setting based on the is_ssl() method.
Notes
- Global. String. $auth_secure_cookie
- Global. wpdb. $wpdb WordPress database abstraction object.
Changelog
Since 2.5.0 | Introduced. |