phpwordpresswordpress-login

How can I create my own error messages for WordPress' login form?


I am making a plugin that aims to improve the security of wordpress sites by limiting the amount of incorrect login attempts a user makes.

else if ($row[2] > $maxtries && $curdate < $row[4]){

            echo '<p>You have been blocked due to continued incorrect login attempts.</p>';
            echo $password;

            $denied_message = "SORRY MATE YA BLOCKED";
            WP_Error( 'denied_access',$denied_message);

        }

At the moment I am just getting a white screen (produced by the WP_Error) with my blocked echo, I would want the login form to display my own error message, the same way it is already done on the wordpress login form. Many thanks.

enter image description here


Solution

  • This is the code I use. Replace 1 == 1 with your conditions!

    add_filter( 'authenticate', 'my_validate_login_form', 10, 3 );
    
    function my_validate_login_form( $user, $username, $password ) {
    
        /**
         * If the username or password are not sent we do nothing (and return $user)
         * This way we avoid errors to be shown before the user clicks the button to log in
         */
        if ( ! isset( $username ) || '' == $username || ! isset( $password ) || '' == $password ) {
            return $user;
        }
    
        // Check if the conditions are true and show an error and cancel further processing if they are
        if ( 1 == 1 ) {
            remove_action( 'authenticate', 'wp_authenticate_username_password', 20 );
            remove_action( 'authenticate', 'wp_authenticate_email_password', 20 );
            $user = new WP_Error( 'denied', '<strong>ERROR</strong>: My awesome error here.' );
            return $user;
        }
    
        // Return $user to allow wordpress to check password and username
        return $user;
    
    }