Skip Navigation

[Resolved] Edit Users Role by Administrator or Editor

This thread is resolved. Here is a description of the problem and solution.

Problem: I would like to modify the roles associated with a new User when a Form is submitted.

Solution:
Use the cred_save_data API to modify the User's roles.

add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==290)
    {
       $current_user_id = $post_id;
       $current_user_data = get_userdata( $post_id );
       $oldroles = $current_user_data->roles; //here should be just one, as it is the first time you edit this user and it is only one-role
     if( !is_array($oldroles) ) {
        $oldroles = array($oldroles);
      }
     //Add new role after you remove old role
      $u = new WP_User( $post_id );
      foreach( $oldroles as $oldrole ) {
        $u->remove_role( $oldrole );
      }
      $newrole = $_REQUEST['user_select_role'];
      $u->add_role( $newrole );
    }
}

Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data

This support ticket is created 6 years, 4 months ago. There's a good chance that you are reading advice that it now obsolete.

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.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

Author
Posts
#957391
User Role.png

1- I have cred form for creating new users with generic field for choosing specific role of the new user

Generic field in this form:

[cred_generic_field field='user_select_role' type='radio' class='' urlparam='']
  {
  "required":0,
  "validate_format":0,
  "default":["shop_manager"],
  "options":[
  {"value":"editor","label":"editor"},
  {"value":"shop_manager","label":"Shop Manager"}
  ]
  }
  [/cred_generic_field]

2- Everytime a new user created with this form, the actual Role "contributor" get deleted and the selected role will be assigned to that user.

code

// Modify new user role based on custom field selection in CRED
add_action('cred_save_data', 'cred_update_user_role_action',10,2);
function cred_update_user_role_action($user_id, $form_data) {
 
    //create an array of values with all ID's of the Forms you want to check:
  $ids = array("232");
    
  //Check if the current form ID is one of in the above array:
  if (in_array($form_data['id'], $ids) ){

	
  // modify the user role to match the selected option
    $role = $_REQUEST['user_select_role'];
    $u = new WP_User( $user_id );
    $u->remove_role( 'contributor' );
    $u->add_role( $role );
  }
}

now i have added a form for editing users that can be accessed by Administrator and Editor. in This form i have added the above generic field and in the code snippet i have added the Edit Users form ID 290 like following:

// Modify new user role based on custom field selection in CRED
add_action('cred_save_data', 'cred_update_user_role_action',10,2);
function cred_update_user_role_action($user_id, $form_data) {
 
    //create an array of values with all ID's of the Forms you want to check:
  $ids = array("232","290");
    
  //Check if the current form ID is one of in the above array:
  if (in_array($form_data['id'], $ids) ){

	
  // modify the user role to match the selected option
    $role = $_REQUEST['user_select_role'];
    $u = new WP_User( $user_id );
    $u->remove_role( 'contributor' );
    $u->add_role( $role );
  }
}

now when I edit any user and change his Role to a different one for example from Editor to Shop Manager.. then i can see in the backend that this user is now Editor, Shop Manager.

This happens because in my code Snippet we order to remove the role contributor only and keep the new one.

Now how can i edit the user role and delete the current one, not only contributor?

#957915

Well, you would need to get the currently edited user's role, populate a variable with it and remove that, same as you do with "remove_role( 'contributor' );", but:

//populate variable with current user edited role:
$currently_edited_user_role =//get current user edited role;
remove_role(  $currently_edited_user_role );

In a cred_save_data, the current edited user is in $post_id.
Hence, you can use that to get the Users role, and use it in the code as you remove the other roles:

add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==12)
    {
       $current_user_id = $post_id;
       $current_user_data = get_userdata( $post_id );
       $role = $current_user_data->roles;//here should be just one, as it is the first time you edit this user and it is only one-role
       //remove_role( $role );
      //Add other roles only after you cleaned up
    }
}

This is however Custom Code that we cannot fully assist.
Above are examples that need to e adapted, using the Toolset API and WordPress API linked below:
https://codex.wordpress.org/Function_Reference/get_userdata
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data

#957950

I have tried following i am not sure i understand everything tight, could you please show me where is the wrong part.

this doesn't let me save the form also
Error message:
The user was not saved because of the following problem:
You can only edit users with following roles: administrator, editor, author, contributor, shop_manager

add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==290)
    {
       $current_user_id = $post_id;
       $current_user_data = get_userdata( $post_id );
       $role = $current_user_data->roles;//here should be just one, as it is the first time you edit this user and it is only one-role
      remove_role( $role );
      //Add other roles only after you cleaned up
	  $role = $_REQUEST['user_select_role'];
	  $u = new WP_User( $user_id );
	  $u->add_role( $role );
    }
}
#958306

Hi, ignore the error message for now because it's not accurate. Check line 13 in the code above, you are using an undefined variable here:

$u = new WP_User( $user_id );

$user_id is undefined. Should it be $post_id instead? That would make sense in a User form.

This function does not remove a role from a User, it removes a role from the database.

remove_role( $role );

If you want to remove a role from a User, you should call the method from a User object like this:

$u->remove_role( $role );

So you must move this function call after the $u = new WP_User( $user_id) line, and modify the $role variables to get and set the correct roles.

Here is an update:

add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==290)
    {
       $current_user_id = $post_id;
       $current_user_data = get_userdata( $post_id );
       $oldrole = $current_user_data->roles;//here should be just one, as it is the first time you edit this user and it is only one-role
      //Add new role after you remove old role
      $u = new WP_User( $post_id );
      $u->remove_role( $oldrole );
      $newrole = $_REQUEST['user_select_role'];
      $u->add_role( $newrole );
    }
}

Try that and let me know the results.

#958339

I have added this code and it adds the selected role to the user but the old one still there....

add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==290)
    {
       $current_user_id = $post_id;
       $current_user_data = get_userdata( $post_id );
       $oldrole = $current_user_data->roles;//here should be just one, as it is the first time you edit this user and it is only one-role
      //Add new role after you remove old role
      $u = new WP_User( $post_id );
      $u->remove_role( $oldrole );
      $newrole = $_REQUEST['user_select_role'];
      $u->add_role( $newrole );
    }
}
#958357

Turn on server logs to see what's happening. Here's a code update that should give you some clues.

add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==290)
    {
       $current_user_id = $post_id;
       $current_user_data = get_userdata( $post_id );
       $oldrole = $current_user_data->roles;//here should be just one, as it is the first time you edit this user and it is only one-role
      error_log(print_r($oldrole, true));
      //Add new role after you remove old role
      $u = new WP_User( $post_id );
      $u->remove_role( $oldrole );
      $newrole = $_REQUEST['user_select_role'];
      $u->add_role( $newrole );
    }
}

If you're not familiar with server logs, I can show you how to activate them temporarily. Go in your wp-config.php file and look for define(‘WP_DEBUG’, false);. Change it to:

define('WP_DEBUG', true);

Then add these lines, just before it says 'stop editing here':

ini_set('log_errors',TRUE);
ini_set('error_reporting', E_ALL);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');

Submit the form again. Now you should find an error_log.txt file in your site's root directory. Please send me its contents. Once that is done, you can revert the changes you made to wp-config.php.

#958369

here is the content of the error_log.txt file

[29-Jul-2018 21:38:11 UTC] PHP Notice:  Use of undefined constant CHILD_THEME_VERSION - assumed 'CHILD_THEME_VERSION' in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 8
[29-Jul-2018 21:39:05 UTC] PHP Notice:  Use of undefined constant CHILD_THEME_VERSION - assumed 'CHILD_THEME_VERSION' in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 8
[29-Jul-2018 21:39:07 UTC] PHP Notice:  Use of undefined constant CHILD_THEME_VERSION - assumed 'CHILD_THEME_VERSION' in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 8
[29-Jul-2018 21:39:30 UTC] PHP Notice:  Use of undefined constant CHILD_THEME_VERSION - assumed 'CHILD_THEME_VERSION' in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 8
[29-Jul-2018 21:39:30 UTC] PHP Notice:  Trying to get property of non-object in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 4
[29-Jul-2018 21:40:10 UTC] PHP Notice:  Use of undefined constant CHILD_THEME_VERSION - assumed 'CHILD_THEME_VERSION' in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 8
[29-Jul-2018 21:40:10 UTC] PHP Notice:  Trying to get property of non-object in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 4
[29-Jul-2018 21:40:10 UTC] PHP Notice:  Undefined index: post_status in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 6
[29-Jul-2018 21:40:10 UTC] Array
(
    [0] => editor
)

[29-Jul-2018 21:40:12 UTC] PHP Notice:  Use of undefined constant CHILD_THEME_VERSION - assumed 'CHILD_THEME_VERSION' in /home3/tatly/tat.ly/30/wp-content/plugins/code-snippets/php/snippet-ops.php(352) : eval()'d code on line 8
#958370

Okay thank you, I have an update that should fix that:

add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
    // if a specific form
    if ($form_data['id']==290)
    {
       $current_user_id = $post_id;
       $current_user_data = get_userdata( $post_id );
       $oldroles = $current_user_data->roles; //here should be just one, as it is the first time you edit this user and it is only one-role
     if( !is_array($oldroles) ) {
        $oldroles = array($oldroles);
      }
     //Add new role after you remove old role
      $u = new WP_User( $post_id );
      foreach( $oldroles as $oldrole ) {
        $u->remove_role( $oldrole );
      }
      $newrole = $_REQUEST['user_select_role'];
      $u->add_role( $newrole );
    }
}
#958371

YES this has fixed the Isuue christian, Thanks! according to the other code that didn't work on my site is it because something weird on my site going on? or its just something that was really missing? because you told me that code worked fine on your site!

#958372

It was just an error in the code because I didn't read the WordPress documentation closely enough 🙂 I don't think there's anything unusual to worry about on your site.

#958373

Anyway you know exactly what needs to be done to fix this! THANKS A LOT 🙂