On log in I want to check a third party data source (table in the db) for a user, and if found I want to add a role to that user.
I don't want to guess the rid of the role, I want to get it from the role name.
This is quite straightforward with user_roles() and array_search(). Below is a function which will return the role ID if there is a role matching the name and FALSE otherwise.
function get_role_by_name($name) {
$roles = user_roles();
return array_search($name, $roles);
}
// Sample usage
$rid = get_role_by_name('administrator');
One liner would be:
$rid = array_search('administrator', user_roles());
Knowing the machine name of the role, it is enough to use user_role_load_by_name()
.
if ($role = user_role_load_by_name('Role Name')) {
// The role ID is in $role->rid.
}
If the Role might not exist...
$role = user_role_load_by_name('Role Name');
$role_id = $role ? $role->rid : NULL;
The best way to identify role and its id is from SQL. Run this query in your SQL editor.
select * from roles;
And you will get the list of Roles including the id and weight.