How can I programmatically get a list of member entities of an Organic Group?

(I know how to get a list of group members using Views — I'd prefer to do this using the Organic Groups API, but haven't been able to find the right method.)


Using directly the Organic Groups API:

og_get_group_members_properties($yourGroupNode, array(), 'members', 'node');

gives you an array of user ids.

To obtain only active, pending or blocked users, you can put 'members__1', 'members__2' or 'members__3' in place of 'members', like in this example:

og_get_group_members_properties($yourGroupNode, array(), 'members__1', 'node');

of, if you prefer, like this one:

og_get_group_members_properties($yourGroupNode, array(), 'members__' . OG_STATE_ACTIVE, 'node');

Example of the returned value:

    [0] => 48
    [1] => 49
    [2] => 51
  • 1
    This should be the correct answer – Chris Apr 21 '15 at 2:42

Or via DBTNG:

$query = db_select("og_membership", "ogm");
$query->condition("ogm.gid", $yourGroupID, "=");
$query->condition("ogm.group_type", "node", "=");
$query->fields("ogm", array("entity_type", "etid"));
$result = $query->execute();

...which allows you to join other tables, rather than having to filter the result set in PHP code as you would if using EntityFieldQuery.

$query = new EntityFieldQuery();
  ->entityCondition("entity_type", "og_membership", "=")
  ->propertyCondition("gid", $yourGroupID, "=");
$result = $query->execute();

(Based on http://api.drupal.org/api/drupal/includes--common.inc/function/entity_load/7#comment-14544)


smokris solution worked but I found another way with EntityFieldQuery:

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->fieldCondition('og_group_ref', 'target_id', $yourGroupID)

Example of the returned value:


Extending answer from @smokris.

The active status for the memberships is "1" (->condition('ogm.state', 1, '=') ).

function _get_users_in_group($gid) {
  $query = db_select('users', 'u');

    ->condition('u.uid', 0, '<>')
    ->condition('u.status', 1, '=')
    ->condition('ogm.state', 1, '=')
    ->fields('u', array('uid', 'name'))
    ->join('og_membership', 'ogm', "ogm.gid = :gid AND u.uid = ogm.etid AND ogm.entity_type = 'user'", array(':gid' => $gid));
  return $query->execute();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.