Logging in users programmatically in WordPress using wp_signon

The wp_signon function in WordPress is used to authenticate a user and sign them into the system. It verifies the user’s credentials and creates a secure session for them, allowing them to access restricted areas or perform specific actions within the WordPress site.

This function can be useful for creating custom login forms, implementing single sign-on solutions, or integrating external authentication systems with WordPress. It provides a way to programmatically authenticate users without relying on the default login page.

Parameters Accepted by wp_signon Function

  • $credentials (array, optional. Default value: array()): User info in order to sign on.

    • user_login (string): Username.
    • user_password (string): User password.
    • remember (bool): Whether to ‘remember’ the user. Increases the time that the cookie will be kept. Default false.
  • $secure_cookie (string|bool, optional. Default value: ”): Whether to use secure cookie.

Value Returned by wp_signon Function

The function returns either a WP_User object on success, or a WP_Error object on failure.

Examples

How to use wp_signon to log in a user

Use the wp_signon function to log in a user with their username and password.

$user = wp_signon( array(
 'user_login' => 'username',
 'user_password' => 'password',
 'remember' => true
) );

if ( is_wp_error( $user ) ) {
 echo $user->get_error_message();
}

How to use wp_signon with custom user meta data

Use the wp_signon function to log in a user and include their custom user meta data.

$user_data = array(
 'user_login' => 'username',
 'user_password' => 'password',
 'remember' => true
);

$user = wp_signon( $user_data );

if ( ! is_wp_error( $user ) ) {
 $user_id = $user->ID;
 $user_meta = get_user_meta( $user_id, 'custom_meta_key', true );
 // Do something with the user meta data
} else {
 echo $user->get_error_message();
}

How to use wp_signon with redirect after login

Use the wp_signon function to log in a user and redirect them to a specific page after successful login.

$user = wp_signon( array(
 'user_login' => 'username',
 'user_password' => 'password',
 'remember' => true
) );

if ( ! is_wp_error( $user ) ) {
 wp_redirect( home_url( '/dashboard' ) );
 exit;
} else {
 echo $user->get_error_message();
}

Conclusion

In conclusion, the wp_signon function is an effective component for managing user authentication and login processes in WordPress. By providing a flexible and secure way to sign users into the system, it allows developers to create custom login forms and integrate with third-party authentication systems. With its ability to handle various authentication methods and return detailed error messages, wp_signon is a valuable function for any WordPress project. By understanding its parameters and return values, developers can leverage this function to create a seamless and secure user experience on their websites.

Related WordPress Functions