Change User Role When Form Submitted

Labels

This Discussion is public

Notifications

I want to enable an active user to change / advance his/her role after completing a form.

I bought the Formidable User Reg plugin, but it doesn't seem to work for changing user roles.

I found and added the code snippet below hoping to accomplish this, but instead of changing the user's role, it sets the role to "None" but adds the role that I had defined for them ("member" in the code below") as a "capability".

Any help would be greatly appreciated.

 

HERE'S THE SNIPPET:

/** * This will change an inactive user to a member after they complete their member profile. */

add_action('frm_after_create_entry', 'inactive_to_member', 20, 2);

function inactive_to_member($entry_id, $form_id){

if($form_id == 24){ //change 24 to the form id of the form to copy

$new_role = 'member'; //change this to the role users should be granted upon completing form

$user = wp_get_current_user(); //get logged in user

if(!$user) {

return; //don't continue if user doesn't exist

}

$updated_user = (array)$user;

// Get the highest/primary role for this user

$user_roles = $user->roles;

$user_role = array_shift($user_roles);

if ( $user_role == 'administrator' ) return;

//make sure we don't downgrade any admins

$updated_user['role'] = $new_role;

wp_update_user($updated_user);

}

}

I think that might be happening because you haven't defined the role yet. There are built-in roles that come with Wordpress, and the function can't assign the role of "member" if it hasn't been created/registered yet.  To register a new role first, check out the Codex "add_role" here: https://codex.wordpress.org/Function_Reference/add_role

Reply to this Discussion