0

Trying to change user role based on points. This is working seems fine till it keep increasing points.

The problem happens when if we decrease points it is not changing role back to below stage.

Means if I have 600 points for administrator role and if user earn and role changed to administrator. After than if points goes down to 500 due to some type of negative system it should change role back to below administrator respecting to the point value in condition but this is not happening.

Once role set to upper it is never going down even if point decrease.

global $wpdb;
$pref = self::qa_prefix();
$u = new WP_User($u_id);

$user_point = $wpdb->get_row("SELECT userid, points FROM {$pref}userpoints WHERE userid = {$u_id}");

if(!is_super_admin()) {    

    if($user_point->points >= 600) {
        $u->set_role('administrator');
    } elseif($user_point->points >= 150 && $user_point->points < 600) {
        $u->set_role('editor');                
    } elseif($user_point->points >= 100 && $user_point->points < 150) {
        $u->set_role('contributor');                
    } else {
        $u->set_role('subscriber');
    }

}

Any suggestion or idea please.... :)

  • 1
    Post all of your code please. What is $u? Where does this hook? – s_ha_dum Jul 10 '13 at 18:11
  • 1
    First, make sure the code inside the condition works (by removing the condition). Then, make sure your conditions are working properly, by echoing something inside each, to make sure you're actually reaching the proper place. If both of those things work correctly, and you still have problems, you probably have a ghost living inside your computer. – Michael Lewis Jul 10 '13 at 18:12
  • 2
    Are you certain the code snippet you posted contains the responsible bit? I doubt it. Looks fine. – Johannes Pille Jul 10 '13 at 18:12
  • @s_ha_dum please check my edited question for full code – pixelngrain Jul 10 '13 at 18:36
  • 1
    That isn't all of the code. You are using self so that is a class. To quote myself, "Where does this hook?" – s_ha_dum Jul 10 '13 at 18:41
1

You have to remove the previous role first, then add the new role like

$u = new WP_User( $user_ID);
$role_of_user= $u->roles[0];
$u->remove_role($role_of_user);
$u->add_role('new_role');

If user has more than 1 role then

$u = new WP_User( $user_ID);
foreach($u->roles as $role){
    $u->remove_role($role);
}
$u->add_role('new_role');
  • 1
    By the way just for your knowledge.. set_role() is also working fine. So no need to remove role and add it again. set_role() is enough – pixelngrain Jul 14 '13 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.