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');