Check User Group By Group ID

There are many scenarios where you may need to check what group(s) a user is in. For example, I use this code to check if users are in my “Sponsors” group. If they are, I don’t display any advertisements for them and I show them a shiny purple star.

Snippet Function

use Joomla\CMS\Factory;

/**
 * Checks if current user is in a specific group
 * @param $group - group id to check
 */
function isInUserGroup($group){
    $user = Factory::getApplication()->getIdentity();
    $groups = $user->get('groups');
    if(in_array($group, $groups)){
        return true;
    } else {
        return false;
    }
}Code language: PHP (php)

Example

This is how I display a special image to my site sponsors. On my site, this user group ID is 10. As I’m only using this on this single site, I can do this.

If you’re trying to create a more generic or reuseable application – you’ll need to programmatically figure out the ID you’re looking for some other way.

<?php if (isInUserGroup(10)) : ?>
    <img src="/images/rockstar.webp" alt="You Rock!" />
<?php endif;?>Code language: HTML, XML (xml)
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments