WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Hook for fail and successful login actions (2 posts)

  1. webvitaly
    Member
    Posted 1 year ago #

    I need to log fail and successful login actions.

    What hook is better to use for this?

  2. webvitaly
    Member
    Posted 1 year ago #

    Answer about login actions was given on stackoverflow.

    Duplicating here the answer:

    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)

Topic Closed

This topic has been closed to new replies.

About this Topic