[Drupal] How to add a group content to an organic group programically in Drupal 7

| | 1 min read

Organic Group Module in Drupal allows to create and manage different groups. While creating a content, we can add that content to a group. The og_group() function allows to add a content to a group.

-->

The parameters of the function og_group() includes the following:

  • First parameter is the entity type of the group.
  • Second parameter is the group id.
  • Third parameter is an array of imformation including 'entity_type' can be node, user etc., 'entity' which is the corresponding entity id, and the 'field_name', which specifies the name of the field that holds the group id.
  • Fourth parameter can be true or false, which specifies whether a new membership should be saved or not.

The following is a function that creates a new node of type "group_content" and adds the content to a group.


language = 'und';
  $new_node->type = 'group_content';
  // Set created user
  $new_node->uid = $user->uid;
  $new_node->title = t('Group Content');
  $new_node->body     = t("Sample body");
  $new_node->status       = 1;
  // Saving the node. 
  node_save($new_node);
  
  $values = array(
    'entity_type' => 'node',
    'entity' => $new_node->nid,
    'state' => OG_STATE_ACTIVE,
    'membership_type' => OG_MEMBERSHIP_TYPE_DEFAULT,
    'field_name' => 'og_group_ref'
  );
  // Add the new content to a group called "Group1" with id "100"
  $group_id = 100;
  og_group('node', $group_id, $values);
}
?>

In this example, it creates a new node and adds the node to a group of id 100.