How can I programmatically add users to an organic group?

  • Welcome to Drupal Answers! Since the question is about code, we expect to see the code you wrote so far. If you are asking a question about code before attempting to write code, you are asking the question too early.
    – apaderno
    Feb 10, 2022 at 20:06
  • i have tried this but not working ..$membership = Og::createMembership($gid, $account);$membership->save();
    – ankur
    Feb 11, 2022 at 7:32

1 Answer 1


Something like the following should work; replace $userId & $groupId with approriate values

// Get a User entity via ID
$user = \Drupal\user\Entity\User::load($userId);

// Get a Group entity via ID
$group = \Drupal\group\Entity\Group::load($groupId);

// Add member and save

You can use the following to get the currently logged in userID

$userId = \Drupal::currentUser()->id()
  • Getting error like "Error: Class 'Drupal\group\Entity\Group' not found "i think this above solution for Group module but want to add in Organic Group module (og_group) not in the Group module.
    – ankur
    Feb 10, 2022 at 13:30

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