Programmatically assign a node to an organic group is following my previous question which I have found the solution for Drupal 7, but I am now looking for the same issue in Drupal 6.

How can I programmatically assign a node to an organic group?

I have tried the following and neither of them worked (assuming $target_group is the group ID that I want the $node to be assigned to).

$node->og_groups = array($target_group => $target_group);
$group = node_load($target_group);
$node->og_groups[0] = $target_group;
$node->og_groups_names[0] = $group->title;

What is the proper way to do this?

2 Answers 2


I think that the first option you propose is correct.

$node->og_groups = array($target_group => $target_group);

You're on the right track.
You also have to add a row to the og_ancestry table. Someone posted sample code for Drupal 6 here.

 * Implementation of hook_nodeapi().
function mymodule_nodeapi(&$node, $op, $arg, $page) {
  switch ($op) {
    case 'insert':
      // let's autocreate a Wiki node for our Top wiki page when we create a Group
      if ($node->type == "group") {
        global $user;
        include_once (drupal_get_path('module', 'pathauto') .'/pathauto.inc');
        $path = pathauto_cleanstring($node->title);

        $wiki->type = "wiki";
        $wiki->status = 1;
        $wiki->uid = $user->uid;
        $wiki->name = $user->name;

        $wiki->title = $node->title . " Wiki";
        $wiki->body = t("This is the Wiki for your Community. Any member is allowed to edit this page. Be the first to edit this page by selecting the EDIT tab above and deleting this content and replacing it with your own.");
        $wiki->path = "wiki/" . $path;
        $wiki->og_groups[0] = $node->nid;
        $wiki->og_public = 0;
        $wiki->og_groups_names[0] = $node->title;

        if ($wiki = node_submit($wiki)) {
          $sql = "INSERT INTO {og_ancestry} (nid, group_nid) VALUES (%d, %d)";
          db_query($sql, $wiki->nid, $node->nid);

  • Do you happen to know why this doesn't happen automatically as long as og_nodeapi calls og_save_ancestry, which seems to be doing the exact same thing?
    – Fuzzy76
    Nov 8, 2012 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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