Monday, August 19, 2013

Wordpress: Change current user role with form selection on update (not entry creation)

Wordpress: Change current user role with form selection on update (not
entry creation)

I'm using Formidable forms and have a form that registers users. I can use
a radio button in the registration form to determine what their role will
be. I have a php hook for that. What I need, however, is a php hook that
will change the user role based on radio selection on form entry UPDATE.
My current code only works on entry creation. Here is the code that
assigns roles on registration:
add_filter('frmreg_new_role', 'frmreg_new_role', 10, 2);
function frmreg_new_role($role, $atts){
extract($atts);
if($form->id == 8){
if($_POST['item_meta'][280] == 'Job Applicant')
$role = 'applicant';
}
return $role;
}
"8" is the id of the form itself. "280" is the id of the radio button
field where "Job Applicant" is one of the values. And "applicant" is one
of our site's user roles.
I need an adaptation of this that will change the role after the entry has
already been created, on update. The closest thing I can find is a hook
that changes user role after a successful PayPal payment. I tried to
combine the two but I couldn't get it to work. Here is the PayPal
generated user role changer:
add_action('frm_payment_paypal_ipn', 'change_paid_user_role');
function change_paid_user_role($args){
$new_role = 'contributor'; //change this to the role paid users should
have
if(!$args['pay_vars']['completed'])
return; //don't continue if the payment was not completed
if(!$args['entry']->user_id or !is_numeric($args['entry']->user_id))
return; //don't continue if not linked to a user
$user = get_userdata($args['entry']->user_id);
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);
}
If anybody could point me toward a solution, I'd be very grateful. If any
further info is needed from me, I'm happy to provide what I can.

No comments:

Post a Comment