Load Drupal Organic Group Role By Name

23rd January 2013 - 2 minutes read time

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.

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

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.