How to Print the User Group in Joomla with PHP

print user group joomla

One of our members asked how to display the user group in the Joomla frontend by using PHP.

In this short tutorial, we'll share the snippet that solves the request.

The PHP code

The code below prints the user group from current logged in user. It's a database query that looks for the title values in the prefix_usergroups table:

<?php
// Get user group
$user_  = JFactory::getUser();
$db     = JFactory::getDBO();
foreach($user_->groups as $group){
    $query  = 'SELECT title FROM #__usergroups';
    $query .= ' WHERE id = ' . $group;
    $db->setQuery( $query );
    echo 'User Group: ' . $db->loadResult();
}
?>

To display the group from an specific user, include the user id in JFactory::getUser() method.

For example:

$user_  = JFactory::getUser(101);

Add the code in your template

  • Go to Extensions > Templates > Template (right side of the screen) > Your template details & files.
  • Inside the Editor tab, choose the file where you want to add the code above. In my example, I'm doing it in the index.php file.
1
  • Save when you're done.

Test the end result

Go to your public site and log in to confirm the user group is actually being printed.

How to Print the User Group in Joomla with PHP

Note, if the logged in user belongs to more than one group, the code still will work.