[Drupal] How to add a user to an Organic Group in Drupal 7?

| | 2 min read

Do you want to add a user to an organic group programmatically in Drupal, then here is a solution. In one of my Drupal module I had a requirement to add users programmatically to an organic group. So I have created a custom function in my module for this purpose. This uses the function og_group to add a user entity to a group. Refer the following code. Remember that, you can add only an existing user to a group. It will not create a new user.

/**
     * Adding a user to an Organic group.
     * 
     * @param int $uid.
     *   Integer specifying the user ID.
     * @param int $gid.
     *   The Organic group ID.
     * @param string $group_type.
     *   The entity type of the group.
     *   If group type is not given, then the default group type will be 'node'. 
     * @param string $membership_type.
     *   Type of membership in which the user entity to be added to the group.
     *   If the membership_type is not given, then the default membership_type
     *   will be 'og_membership_type_default'.
     * 
     */
    function my_module_add_user_to_group($uid, $gid, $group_type = NULL, $membership_type = NULL) {
      $group = node_load($gid);
      $user = user_load($uid);
      if (!$group_type) {
        $group_type = 'node';
      }
      if (!$membership_type) {
        $membership_type = OG_MEMBERSHIP_TYPE_DEFAULT;
      }
      $is_a_group = $group->group_group[$group->language][0]['value'];
      // Checking whether $group is an organic group and the $user object exists.
      if ($is_a_group && $user) {
        $values = array(
          'entity_type' => 'user',
          'entity' => $user,
          'state' => OG_STATE_ACTIVE,
          'membership_type' => $membership_type
        );
        og_group($group_type, $gid, $values);
      }
      return;
    }

The above function will add the user to the group only if $gid is a valid group id and $uid is a valid user id.