2

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');
2
  • you need to add 1 in account_activated meta value for existing users
    – Akshat
    Jun 30, 2018 at 12:27
  • I am doing that
    – Philipp K
    Jun 30, 2018 at 13:04

1 Answer 1

3

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');
3
  • I tried that but it doesn't work
    – Philipp K
    Jun 30, 2018 at 13:03
  • @PhilippK Notice that you need to remove the $userStats = 1; I did it for testing.
    – Shibi
    Jun 30, 2018 at 13:30
  • I did remove it. However, I was getting excited too soon. This code lets users log in even if they haven't confirmed their email. Edit: Nevermind, forgot to change the hook. Works fine now
    – Philipp K
    Jun 30, 2018 at 13:33

Your Answer

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

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