A while back ago I was needing to display a message to logged in registered users belonging to a specific user group.

If the registered user was not part of the specified user group, then the message would not appear.

In this post I'll share with you my solution

The getUser() Method

Joomla makes it super easy to get the current registered user's group id with the getUser() method of the Factory class.

To be a bit more specific, the user group id number (of a current registered user) will be an associative array value of the getUser() method.

To access the values of an associative array, we need to use a php foreach loop.

Keeping this in mind, I started off by placing the following code snippet atop the site template's index.php file:

Joomla! 3 php
  use Joomla\CMS\Factory;
  $user = Factory::getUser();

  foreach ($user->groups as $key => $value) {
  echo $key;

I then logged in to the front end of the site and saw my user group id number atop of the page.

Now, in case you're wondering, the above code snippet does the following:

  • Lines 2-3: Get the user object of the current logged in user.
  • Lines 5-6: Loop thru' the groups array (of the getUser() method) and display the user group id number(s).

Of course, this code snippet doesn't target any specific user group, it just outputs the current user's group id number and nothing more.

Targeting A Specific User Group

So that I could display the message to a specific user group, the script needs to know the following:

  • Which user group's id number will be allowed to see the message.
  • The current logged in user's group id number.
  • Check if both group id numbers match.
  • If they match, then allow the user to see the message.

This can easily be accomplished by storing the targeted group id number in a variable that an if statement can access.

The if statement's condition, will be an in_array() function that will check if both the current user and targeted user group id numbers match.

If both numbers match, then the current registered user gets to see the message. If it doesn't match, well you know, the user doesn't see it.

The final (generic) code snippet that targets users from a specific group is:

Joomla! 3 php
  use Joomla\CMS\Factory;
  $user = Factory::getUser();
  // allowed user group id number
  $userGroupId = 1;

  // group ids match, do this
  if(in_array($userGroupId, $user->groups)){ 
  echo "In The Group";
  // group ids don't match, do this
  echo "Not In The Group";

Easy peasy, right? Remember, if you use the above code snippet -you've got to change the $userGroupId variable value to the group id number you want to target.