skip to Main Content

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


  1. Try the following revisited 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 && ! array_intersect(['administrator','subscriber'], $current_user->roles )
        && floatval($current_user->current_my_wallet_balance) < 0 ) {
            $current_user->set_role( 'subscriber' );
        }
    }
    

    This code is tested and works flawlessly in all possible cases, without throwing any errors.

    Login or Signup to reply.
    1. 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.

    2. There is no need for a new WP_User, that object already exists for the current user via wp_get_current_user().

    3. Also exclude subscribers from the condition to avoid setting the same role over and over again.

    4. You can cast get_user_meta to int and then use <0 for comparison.

    add_action('init', 'changerole');
    function changerole() {
        $user = wp_get_current_user();
        if (!in_array('administrator', (array)$user->roles) &&
            !in_array('subscriber', (array) $user->roles)) {
            $balance = (float)get_user_meta($user->ID, 'current_my_wallet_balance', true);
            if ($balance < 0) { 
                $user->set_role('subscriber');
            }
        }
    }
    
    

    Edit: Just saw the edits to your question. You probably should now cast to float instead of int.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search