wp_signon

Home » Functions » wp_signon

Function Name: wp_signon

Explanation: The wp_signon function is a WordPress core function that allows a user to authenticate and sign in to a WordPress website programmatically. It checks the provided credentials against the user database and if the credentials are valid, it creates a new session for the user, making them logged in.

This function is primarily used when you want to implement custom login functionality or automate the login process for users on your WordPress site. It can be used in scenarios where you need to log in a user automatically after a specific event or when integrating external systems with WordPress.

The wp_signon function takes an array of parameters as an argument, including the user login name or email and the user password. It returns a WP_Error object if the authentication fails, and a WP_User object if the authentication is successful.

Example Usage:

// Prepare the user credentials
$credentials = array(
    'user_login'    => 'john_doe',
    'user_password' => 'password123',
    'remember'      => true, // Optional: remember the user for future sessions
);

// Attempt to sign in the user
$user = wp_signon($credentials);

// Check if sign-in was successful
if (is_wp_error($user)) {
    echo 'Authentication failed: ' . $user->get_error_message();
} else {
    echo 'User logged in successfully!';
    // Perform any additional actions for the authenticated user
}

In the example above, we first prepare the user credentials by providing the login name or email and the password. We also set the ‘remember’ parameter to true, indicating that we want the user to be remembered for future sessions.

Next, we call the wp_signon function and pass the credentials array. If the authentication is successful, the function returns a WP_User object representing the authenticated user. We can then proceed with our logic for the authenticated user, such as displaying a success message or performing specific actions.

On the other hand, if the authentication fails, the function returns a WP_Error object. We can use the is_wp_error function to check if the returned value is an error object and display an appropriate error message using the get_error_message method.

Remember, when using wp_signon, it’s important to handle user input securely and validate the credentials before calling the function to ensure the security of your WordPress site.

Learn More on WordPress.org

WordPress snippets using the wp_signon function

Register an account to save your snippets or go Pro to get more features.