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);
2
Answers
Try the following revisited code, that will change "customer" user role to "subscriber", if its wallet balance is below
0
:This code is tested and works flawlessly in all possible cases, without throwing any errors.
You shouldn’t be using
current_user_can()
for user roles anymore (though it never worked flawlessly for roles, it now is for capabilities only, according to documentation). Check with$user->roles
instead.There is no need for a
new WP_User
, that object already exists for the current user viawp_get_current_user()
.Also exclude
subscribers
from the condition to avoid setting the same role over and over again.You can cast
get_user_meta
toint
and then use<0
for comparison.Edit: Just saw the edits to your question. You probably should now cast to
float
instead ofint
.