最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - Set "editor" role to existing user

programmeradmin1浏览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?

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?

Share Improve this question asked Apr 19, 2019 at 20:42 32454325342523245432534252 1174 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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');
发布评论

评论列表(0)

  1. 暂无评论