Check for user meta data at Login

On my website, users have a meta data attribute that is set to either true or false depending on whether they have confirmed their email address or not. I'm trying to not let them log in if they have not confirmed their email but let them log in if they have.

To accomplish this, I have added the following code to my functions.php file. However, with this in place, it won't let anyone log in. Where is the mistake?

<?php
function isUserActivated($user){
    $userStatus = get_user_meta($user, 'account_activated', true);
    $login_page  = home_url('/login/');
    if($userStatus == 0){
        wp_redirect($login_page . "?login=failed");
        exit;
    }
}

add_filter('wp_authenticate_user', 'isUserActivated');

Answers 1

  • If you use the filter wp_authenticate_user you get the user object you need to use the user ID to get the user meta

    function isUserActivated($user){
        $userStatus = get_user_meta($user->ID, 'account_activated', true);
    
        // for testing $userStatus = 1;
        $login_page  = home_url('/login/');
        if($userStatus == 0){
            wp_redirect($login_page . "?login=failed");
            exit;
        }
    
        return $user;
    }
    
    add_filter('wp_authenticate_user', 'isUserActivated');
    

    But I think better use the action wp_authenticate because its run before the authenticate filter.

    function isUserActivated($username){
    
        // First need to get the user object
        $user = get_user_by('login', $username);
        if(!$user) {
            $user = get_user_by('email', $username);
            if(!$user) {
                return $username;
            }
        }
    
        $userStatus = get_user_meta($user->ID, 'account_activated', true);
    
        //for testing $userStatus = 1;
        $login_page  = home_url('/login/');
        if($userStatus == 0){
            wp_redirect($login_page . "?login=failed");
            exit;
        }
    
    }
    
    add_action('wp_authenticate', 'isUserActivated');
    

Related Questions