How To Get the Current User's Group

hearty fare

Get User Group

There are times you need to get the current user's group or groups. For example, if you want to display a list of users belonging to the same group.

nort90 asked...

I use Login modx. When user login i can see this [[+username]], but I need User Group.

The Solution:

BobRay says...

$modx->user is always set in the front end, but may not work if the user isn't logged in (and you're not logged in if you're previewing from the Manager).

Try this:

    if ($modx->user->get('username') !== '(anonymous)') {
     $modx->setPlaceholder('user.groupnames', implode(', ', $modx->user->getUserGroups()));
} else {
    $modx-setPlaceholder('user.goupnames', '(anonymous) user - no groups';

What's the Story?

You can get a user's groups using the API function like this:


However, if the user isn't logged in to the context where the page is being viewed, there won't be a user object. So there needs to be checks in the code to make sure that the user is in fact logged in to the context to avoid nasty errors.

More recent versions of MODX allow a System Setting to set the username of a not-logged-in visitor, so it would be better to use the setting value in the code:

  if ($modx->user->get('username') !== $modx->getOption('default_username'))