Skip Navigation

[Resolved] How to change user role with frontend cred user edit form

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

Author
Posts
#2612733

Hi!
I am attempting to change the user role of the currently logged-in user using a CRED form on the frontend.

I understand that I need to use custom code in the form of a snippet, and I have created one with the assistance of AI. However, it is not working as expected.

Could you please review the code and identify any mistakes? Here is my code:

add_action('cred_save_data', 'change_user_roles', 10, 2);
function change_user_roles($post_id, $form_data) {
if ($form_data['id'] == '137') { // Replace 'form_ID' with the ID of your form
$current_user = wp_get_current_user();
$user_id = $current_user->ID; // Get the ID of the current logged-in user
$selected_roles = $form_data['fields']['select-user-role']; // Replace 'checkbox_field_name' with the identifier of your Checkbox Group field

$user = new WP_User($user_id);

// Set the selected user roles for the user
$user->set_role($selected_roles);
}
}

I would appreciate your assistance in identifying any errors.
Thank you.

P.S.
I use group of checkboxes (Custom Fields Group>User fields> checbox group with slug select-user role) with Titles identical with names of existing user roles...
ID number of CRED edut user form is 137.

#2612889
user-field-example.png

Hi,

Thank you for contacting us and I'd be happy to assist.

On my test website, I managed to make this code work, after some changes.

Important note: Make sure to save the slugs of the available roles, as options in the 'checkboxes' field settings, as shown in the attached screenshot.


add_action('cred_save_data', 'change_user_roles', 10, 2);
function change_user_roles($post_id, $form_data) {
	if ($form_data['id'] == '12345') { // Replace 'form_ID' with the ID of your form
		// get field value from 'select-user-role'
		$user_field_val = types_render_usermeta( "select-user-role", array( "separator" => "," , "user_id" => $post_id ) );
		// check if some field value exists
		if(!empty($user_field_val)) {
			// get user's info
			$user = new WP_User($post_id);
			// create an array of the field value from 'select-user-role'
			$user_field_val_arr = explode(',', $user_field_val);
			// loop through the selected roles, so that the first one is set as the main role, removing any previous roles and rest are added as additional roles
			for ($i=0; $i < sizeof($user_field_val_arr) ; $i++) { 
				if( $i == 0 ) {
					$user->set_role($user_field_val_arr[$i]);
				} else {
					$user->add_role($user_field_val_arr[$i]);
				}
			}
		}
	}
}

Important note: The code will not update user roles if none of the options from that user field is selected. It is a good idea to also include some custom script, to make sure that form can't be submitted unless at least one of those options is selected.

I hope this helps and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/

regards,
Waqar

#2612985
snippet.PNG
Checkbox group.PNG

Thank you for the function, but it is not working as expected.
It does not change the user role.
I have updated the "Value to store" to match the actual slugs of the created user roles (screenshot attached), and I have changed the form ID to the actual value of 137.
Please note that the function should change the user role of the currently logged-in user.

#2613483

Thanks for writing back.

From the screenshots, I noticed that your field's slug is 'select-user-roles', but in the code snippet 'select-user-role' is being used.

Please update all instances of 'select-user-role' to 'select-user-roles' so that they match and then test the form again.

#2614305

I apologize, I didn't realize there was a mistake in one letter of the slug.
Thank you so much, the code is working and it changes the user roles.

"Additional requirements:

1. To keep the default user role (contributor) while allowing other roles to be added and/or removed. Even though I didn't include contributor in the form, it still removes default user role and adds the default user role option to the first selected role.
2. Your suggestion under the 'Important note' in your previous response.
3. Since the form for changing user roles is on a custom post published by the author, how can I restrict the accesss of those user roles only to that specific post for the logged-in user?" (Example:The owner of a gym publishes a custom post/listing of his gym, and a logged-in user wants to sign up as a trainer, trainee, assistant, etc., so only for that specific custom post of a particular author."

Hope this is not too much...
Regards,

Sinisa

New threads created by Waqar and linked to this one are listed below:

https://toolset.com/forums/topic/split-how-to-restrict-access-to-the-form-for-specific-user-roles/

#2614963

Thanks for the update and glad that the code is working now.

> 1. To keep the default user role (contributor) while allowing other roles to be added and/or removed. Even though I didn't include contributor in the form, it still removes default user role and adds the default user role option to the first selected role.

- If you'd like the 'contributor' role to always be added by the form, as the primary one, regardless of the selected options, you can update the code snippet from my last reply to:


add_action('cred_save_data', 'change_user_roles', 10, 2);
function change_user_roles($post_id, $form_data) {
	if ($form_data['id'] == '137') { // Replace 'form_ID' with the ID of your form
		// get field value from 'select-user-roles'
		$user_field_val = types_render_usermeta( "select-user-roles", array( "separator" => "," , "user_id" => $post_id ) );
		// check if some field value exists
		if(!empty($user_field_val)) {
			// get user's info
			$user = new WP_User($post_id);
			// set default user role 'contributor'
			$user->set_role('contributor');
			// create an array of the field value from 'select-user-roles'
			$user_field_val_arr = explode(',', $user_field_val);
			// loop through the selected roles to add them as additional roles
			for ($i=0; $i < sizeof($user_field_val_arr) ; $i++) { 
				$user->add_role($user_field_val_arr[$i]);
			}
		}
	}
}

> 2. Your suggestion under the 'Important note' in your previous response.

- You can use the filter 'cred_form_validate' for this purpose too:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate

For example:


add_filter('cred_form_validate','change_user_roles_validation',10,2);
function change_user_roles_validation($error_fields, $form_data)
{
	//field data are field values and errors
	list($fields,$errors)=$error_fields;
	//validate if specific form
	if ($form_data['id']==137)
	{
		// if no option is selected for the 'select-user-roles' field
		if( empty($fields['wpcf-select-user-roles']['value'])  ) {
			$errors['wpcf-select-user-roles'] = 'At least one role needs to be selected!';
		}
	}
	//return result
	return array($fields,$errors);
}

The above code will check the form submission and if none of the options from the 'select-user-roles' field are selected, it will show the error message.

For your third question, I've created a separate ticket and will follow up on that shortly.
( ref: https://toolset.com/forums/topic/split-how-to-restrict-access-to-the-form-for-specific-user-roles/ )

#2614977

Thank you so much for the work done. Just to emphasize, under point 3, what I want is that after submitting the CRED form on a specific post, those user roles and the access they allow should only apply to the user who submitted the form and only for that post.

#2615013

You're very welcome.

For point 3, I'll follow up on its respective ticket.

Feel free to mark this ticket as resolved and start a new one for each new question or concern.

#2616133

My issue is resolved now. Thank you!