I use a wallet system on my website, how can I change the user's role if his balance has dropped below 0
? The meta_value can take a value from -500
to 0
.
add_action('init', 'changerole');
function changerole() {
if(!current_user_can('administrator')) {
$user_id = get_current_user_id();
$user_meta = get_user_meta($user_id, 'current_my_wallet_balance', true);
if ( $user_meta == 0) { //Which operator can I use?
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );
}
}
}
That doesn't work either:
$user_meta = min(max($user_meta , -500), 0);
Try the following revised code, that will change "customer" user role to "subscriber", if its wallet balance is below 0
:
add_action('init', 'change_user_role_based_on_wallet_balance');
function change_user_role_based_on_wallet_balance() {
global $current_user;
if( $current_user && count(array_intersect(['adminisfqtrator','subscriber'], $current_user->roles)) === 0
&& floatval($current_user->current_my_wallet_balance) < 0 ) {
$current_user->set_role( 'subscriber' );
}
}
Tested and works.