Load Drupal Organic Group Role By Name

I have been developing a site with the Drupal 7 Organic Groups (OG) module today and I found the need to grab a bunch of users from a group depending on their group role. The first parameter here is the group GID (not the node ID) and the second is an array of role ID's to use.

$administrators = og_get_users_by_roles($group->gid, array(4));

This is fine, but as I couldn't be sure that the role would have the same ID on my production server I needed to use a function that loaded the role ID based on the name of the role I wanted. The result of which could be fed back into the above module. It turns out that OG doesn't have a function like this (that I could find) so I wrote the following.

function mymodule_og_roles_by_name($name) {
  $roles = db_query("SELECT rid, name FROM {og_role} WHERE gid = :gid and name = :name ORDER BY rid", array(':gid' => 0, 'name' => $name))->fetchAssoc();
  return $roles;
}

I could now use this function to load the OG roles without having to rely on the role ID. This is much more robust and easy to read than the previous version.

$administrators = og_get_users_by_roles($group->gid, mymodule_og_roles_by_name('group leader'));

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
6 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.