I need to log fail and successful login actions.
What hook is better to use for this?
There are a few different hooks you can use (from wp_signon
):
wp_authenticate
(action)authenticate
(filter)wp_login
(action)But you may do best to override the pluggable wp_authenticate
(from wp-includes/pluggable.php
):
if ( !function_exists('wp_authenticate') ) :
/**
* Checks a user's login information and logs them in if it checks out.
*
* @since 2.5.0
*
* @param string $username User's username
* @param string $password User's password
* @return WP_Error|WP_User WP_User object if login successful, otherwise WP_Error object.
*/
function wp_authenticate($username, $password) {
$username = sanitize_user($username);
$password = trim($password);
$user = apply_filters('authenticate', null, $username, $password);
if ( $user == null ) {
// TODO what should the error message be? (Or would these even happen?)
// Only needed if all authentication handlers fail to return anything.
$user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
}
$ignore_codes = array('empty_username', 'empty_password');
if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
do_action('wp_login_failed', $username);
}
return $user;
}
endif;
All you would need to do is define your own wp_authenticate
mimicking the actions and adding a few lines to do your logging. That is assuming you don't already have a function that is overriding it.
And as you can see right in the above code, you could use:
wp_login_failed
(action)wp-includes/pluggable.php
you add that function in your own theme or plugin. If it's in your own theme or your own plugin it will not be overwritten by WordPress on update. You would add that code without the conditional check.
You can use action wp_login
Here is the code example
function after_login( $user_login, $user) {
echo "<br/>Username: $user_login";
echo "<br/>user obj: "; print_r($user);
}
add_action('wp_login', 'after_login', 10, 2);