How to programmatically add a user to a group in Drupal 7 I am trying to programmatically create a group node and add a user to that group in Drupal 7. The group node is being created just fine but the user is not being added to the group and I am not getting any errors. I am guessing I am using the og_group function incorrectly but I am not sure. What am I doing wrong?

function MYMODULE_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node-&gt;type     = "group";
    $node-&gt;uid      = $user-&gt;uid;
    $node-&gt;title        = t("Group Node Title");
    $node-&gt;body     = t("Group Node Body");
    $node-&gt;status       = 1;
    $node-&gt;promote      = 0;
    $node-&gt;comment      = 1;

    $node-&gt;og_description   = t("OG Description");
    $node-&gt;og_register  = 0;
    $node-&gt;og_directory = 0;
    $node-&gt;og_private   = 1;
    $node-&gt;og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    $account = user_load(2);

    og_group($node-&gt;nid, array(
                "entity type"       =&gt; "user",
                "entity"        =&gt; $account,
                "membership type"   =&gt; "OG_MEMBERSHIP_TYPE_DEFAULT",
            ));

    drupal_set_message(t("Finished"));
}
I figured it out. It ended up not working because the group ID is NOT the same as the node ID for that organic group. Here is the working version:

function MYMODULE_page_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node-&gt;type     = "group";
    $node-&gt;uid      = $user-&gt;uid;
    $node-&gt;title        = t("Group Node Title");
    $node-&gt;body     = t("Group Node Body");
    $node-&gt;status       = 1; //(1 or 0): published or not
    $node-&gt;promote      = 0; //(1 or 0): promoted to front page
    $node-&gt;comment      = 1; //2 = comments on, 1 = comments off

    $node-&gt;og_description   = t("OD Description");
    $node-&gt;og_register  = 0;
    $node-&gt;og_directory = 0;
    $node-&gt;og_private   = 1;
    $node-&gt;og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    // Get the group ID from the node ID
    $group = og_get_group("node", $node-&gt;nid);

    // Load the user we want to add to the group (ID #2 was my test user)
    $account = user_load(2);

    // Add the user to the group
    og_group($group-&gt;gid, array(
                "entity type"       =&gt; "user",
                "entity"        =&gt; $account,
                "membership type"   =&gt; OG_MEMBERSHIP_TYPE_DEFAULT,
            ));

    // Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
    og_role_grant($group-&gt;gid, $account-&gt;uid, 3);

    drupal_set_message(t("Finished"));
}