Use code "BFCM22" "BFCM22" "BFCM22" to Get 22% OFF

Block users with negative balances

Navigation:

Description

In this tutorial, I will show you how you can block users from logging in if their account balance goes into minus.

For this tutorial, we will assume that our myCred installation has hooks which deduct points from users, creating the possibility of user’s accounts going minus.

Requirements

  • Hooks that deduct points from users creating the possibility for users accounts to go minus.

Authenticate

For this feature we will need to hook into WordPress using the authenticate filter. This filter fires when the user has entered their username and password and clicked “Login”. Our filter will check the users point balance and if it is below zero, we will return an error message which will prevent the user from logging in. Place the following code snippet into your theme’s function.php file.

/**
 * Block Negative Balances
 * Stop users from logging into your website if they have a negative
 * myCRED balance.
 * @version 1.0
 */
add_filter( 'authenticate', 'mycred_block_negative_balances', 990, 3 );
function mycred_block_negative_balances( $user, $username, $password ) {

 	// Make sure myCred is installed
 	if ( ! defined( 'myCRED_VERSION' ) ) return $user;

 	// The point type we want to use
 	$type = 'mycred_default';

 	// Load myCRED
 	$mycred = mycred( $type );
 	$account = get_user_by( 'login', $username );

 	if ( isset( $account->ID ) ) {

 		if ( ! $mycred->exclude_user( $account->ID ) ) {

 		if ( $mycred->get_users_balance( $account->ID, $type ) < 0 )
 			return new WP_Error( 'mycred_negative', __( 'Account Closed' ) );

 		}

 	}

 	return $user;

}

Done

There you have it. It’s as simple as that. You can of course enter your own message to show users and as the commented in the code, you can change it to block users with zero points as well.

11