Skip to content

Assign a user group based on active products

This example adds a user to a group while the user has an active subscription to any of the configured products.

Add this code to site.php file:

Am_Di::getInstance()->hook->add(Am_Event::SUBSCRIPTION_CHANGED, function (Am_Event_SubscriptionChanged $event) {
// Configuration
$productIds = [3, 4, 5]; // Product IDs that trigger group assignment
$groupId = 11; // User group ID to assign
$user = $event->getUser();
if (array_intersect($productIds, $user->getActiveProductIds())) {
$groups = $user->getGroups();
if (!in_array($groupId, $groups)) {
$groups[] = $groupId;
$user->setGroups($groups);
}
} else {
// Uncomment this block to remove the group when none of the
// configured products are active.
// $groups = $user->getGroups();
// if (in_array($groupId, $groups)) {
// array_remove_value($groups, $groupId);
// $user->setGroups($groups);
// }
}
});