Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I hook into the Wordpress login system to stop some users programmatically?

I am working on a Wordpress based portal which integrates with a custom-made e-commerce. The e-commerce serves also as a 'control panel': all the roles are set up there. Some users are recorded but 'inactive'; they shouldn't be able to log into Wordpress. For this reason I need to hook into the Wordpress login system.

If a user is, say, "bad_james", he cannot login, even if he has a valid WP login and PWD. The WP admin panel doesn't provide a a flag to block users.

Is there a way to implement a login filter?

Cheers,
Davide

like image 397
nutsmuggler Avatar asked Nov 26 '09 18:11

nutsmuggler


People also ask

How do I block login on WordPress?

To add the Login/out block, click on the + Block Inserter icon and search for “login”. Click it to add the block to the post or page. Using your keyboard, you can also type /login on a new line and press enter to quickly add a new Login/out block. For more, visit our detailed instructions on adding blocks.

How do I stop WordPress login redirecting?

The quickest way to solve the WordPress login redirect issue is by clearing your browser cookies and cache. WordPress uses cookies to store authentication data. Sometimes your browser might retain old files, resulting in a redirect loop when you try to log in to your site.


2 Answers

You can either overload the wp_authenticate function (see the function in the code here: http://core.trac.wordpress.org/browser/trunk/wp-includes/pluggable.php) and return a WP_error if you don't want to allow the user to login.

Or better, use the filter authenticate and return null if you don't want the user to log in, e.g.

add_filter('authenticate', 'check_login', 10, 3);
function check_login($user, $username, $password) {
    $user = get_userdatabylogin($username); 

    if( /* check to see if user is allowed */ ) {
        return null;
    }
    return $user;
}
like image 127
mjangda Avatar answered Oct 24 '22 01:10

mjangda


There were a few issues with mjangda answer so I'm posting a version that works with WordPress 3.2

The main issues were with the return statement. He should be returning a WP_User Object. The other issue was with the priority not being high enough.

add_filter('authenticate', 'check_login', 100, 3);
function check_login($user, $username, $password) {
    // this filter is called on the log in page
    // make sure we have a username before we move forward
    if (!empty($username)) {
        $user_data = $user->data;

        if (/* check to see if user is allowed */) {
          // stop login
          return null;
        }
        else {
            return $user;
        }
    }

    return $user;
}
like image 24
joeljoeljoel Avatar answered Oct 24 '22 01:10

joeljoeljoel