Eliran Arkabi
Eliran Arkabi

Reputation: 1

get_user_by() return roles as empty array

I get a user with function get_user_by('login', $user_id) and the user object returns the roles as an empty array.

I check in db table usermeta meta_key wp_capabilities has value:

wp_capabilities

And also in table option option_name wp_user_roles has the role of user:

wp_user_roles.

Upvotes: 0

Views: 894

Answers (3)

Yita
Yita

Reputation: 1

global $wpdb;
$user_roles = get_user_meta( $user_id, $wpdb->prefix . 'capabilities', true );

Then you can get role name in array key.

ex: Array( [administrator] => 1 )

So that I use array_keys to convert keys to values:

$user_roles = array_keys( $user_roles );

And now $user_roles same as $current_user->roles

Upvotes: 0

Prathak Godawat
Prathak Godawat

Reputation: 84

You Want user role from user ID. you can easily get it with using This code . Try This

<?php $user_info = get_userdata(1);
      echo 'Username: ' . $user_info->user_login . "\n";
      echo 'User roles: ' . implode(', ', $user_info->roles) . "\n";
      echo 'User ID: ' . $user_info->ID . "\n";
?>

Good Luck

Upvotes: 1

Paul Bamforth
Paul Bamforth

Reputation: 53

If the function was failing then you'd get a return value of false. Are you sure you're getting an empty array? The documentation specifies that an object is returned, maybe save the result in a variable and var_dump it to be sure.

Upvotes: 0

Related Questions