CommonDocs.org

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

1use Joomla\CMS\Factory;
2
3/**
4 * Checks if current user is in a specific group
5 * @param $group - group id to check
6 */
7function isInUserGroup($group){
8    $user = Factory::getApplication()->getIdentity();
9    $groups = $user->get('groups');
10    if(in_array($group, $groups)){
11        return true;
12    } else {
13        return false;
14    }
15}

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.

1<?php if (isInUserGroup(10)) : ?>
2    <img src="/images/rockstar.webp" alt="You Rock!" />
3<?php endif;?>
More in Code Snippets

Get Article Field Values From Anywhere

The following code snippets use Joomla's Database Classes to retrieve information about any article in the __content table of your Joomla database. Note that…

Read guide
Was this guide useful?

Spotted a mistake? Select the sentence in the guide and choose “Suggest a fix”.

Comments

Found an error? instead, it reaches me faster.

No comments yet. Questions and corrections are welcome.