2

I need to log fail and successful login actions.

What hook is better to use for this?

2 Answers 2

6

There are a few different hooks you can use (from wp_signon):

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)
3
  • I want to add parameter in url when user login successfully in wordpress....is there any way?
    – vrajesh
    Jun 19, 2015 at 13:56
  • totels will that custom function get overwritten by wordpress on update? Thanks in advance.
    – kenef
    Oct 26, 2018 at 18:20
  • @kenef You don't add it to 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.
    – Howdy_McGee
    Oct 26, 2018 at 18:54
0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.