0

Using the User ID of an existing user, how do I change the role to Editor?

Here's what I tried:

$wpdb->query("UPDATE wp_usermeta SET meta_value = 'a:1:{s:6:\"editor\";b:1;}' WHERE user_id = '$user_id' AND meta_key = 'wp_capabilities'");

Not sure what I am doing wrong?

0

Usermeta key that stores the user's role has a prefix in the name, the one set in the wp-config.php file. So meta_key will have the form {prefix}_capabilities and your query should look like

global $wpdb;
$wpdb->query(
        $wpdb->prepare(
          "UPDATE {$wpdb->usermeta} SET meta_value = 'a:1:{s:6:\"editor\";b:1;}' WHERE user_id = %d AND meta_key = '{$wpdb->prefix}capabilities'",
          $user_id ) 
);

You do not need to write SQL query. You can achieve the same by fetching the WP_User object with get_userdata function and set new role with the method set_role (or remove_role and add_role to change only one of the roles).

$my_user_id = 12345;   // user ID for changing role
$my_user = get_userdata($my_user_id);
if ( $my_user instanceof WP_User )
    $my_user->set_role('editor');
  • Thank you! The second solution worked perfectly – comdex Apr 20 at 23:10

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.