WordPress Adding custom login authentication

I have added custom fields on registration to allow the user to input their own password and have also created code to generate a verification code which then gets emailed over to the user. Of course, the users needs to click the link in the email before they can log in.

Here’s where I am stuck. I am trying to add my own authentication to check the status of the verification when the user tried to log in.

Read More

Here’s my code which isn’t working;

function check_validation_status($username) {
    $user = get_user_by('login', $username);
    $userID = $user->ID;

    $status = get_user_meta($userID, 'verified', true);

    if($status == '0') {
        return;
    }
}

add_action('wp_authenticate', 'check_validation_status');

Unfortunately this code doesn’t seem to do anything. I have also tried the following (hooking into a different action)

function check_validation_status($username) {
    $user = get_user_by('login', $username);
    $userID = $user->ID;

    $status = get_user_meta($userID, 'verified', true);

    if($status == '0') {
        wp_logout(); // works but doesn't show an error :(
    }
}

add_action('wp_login', 'check_validation_status');

This code is successfulling logging the user straight out if they are not verified however it shows no form of error to the user, they just get redirected straight back to the login page.

Logging the user in but straight back out seems like a sloppy way to do it, is there a way to prevent the log in in the first place?

Related posts

Leave a Reply

1 comment

  1. I have managed to fix this issue now. I instead needed to hook into wp_authenticate_user and return a WP_Error. Here is my working code, I hope it helps someone out in the future.

    function check_validation_status($user, $password) {
        $userID = $user->ID;
    
        $status = get_user_meta($userID, 'verified', true);
    
        if($status == '0') {
            $errors = new WP_Error();
            $errors->add('title_error', __('<strong>ERROR</strong>: This account has not been verified.', 'podium'));
            return $errors;
        }
    
         return $user;
    }
    
    add_action('wp_authenticate_user', 'check_validation_status', 10, 2);