Skip to content

Instantly share code, notes, and snippets.

@jarkkolaine
Created September 18, 2015 11:58
Show Gist options
  • Save jarkkolaine/3d41d130245a131a6cba to your computer and use it in GitHub Desktop.
Save jarkkolaine/3d41d130245a131a6cba to your computer and use it in GitHub Desktop.
A simple code snippet for authenticating a user using email address
public function authenticate_with_email( $user, $email, $password ) {
if ( is_wp_error( $user ) ) {
// Already failed
return $user;
}
if( empty( $email ) || empty ( $password ) ) {
$error = new WP_Error();
if ( empty( $email ) ) {
$error->add( 'empty_username', __( '<strong>ERROR</strong>: Email field is empty.' ) );
}
if ( empty( $password ) ) {
$error->add( 'empty_password', __( '<strong>ERROR</strong>: Password field is empty.' ) );
}
return $error;
}
// Check if user exists in WordPress database and password is valid
// Notice that we look the user up using the email
$user = get_user_by( 'email', $email );
if ( ! $user ) {
// Optional: if no user with this email exists, you can check the username if you like...
$user = get_user_by( 'login', $email );
}
// Check password
if ( ! $user || ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
$error = new WP_Error();
$error->add( 'invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.' ) );
return $error;
}
// User logged in OK
return $user;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment