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
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;?>
Spotted a mistake? Select the sentence in the guide and choose “Suggest a fix”.
Related guides
Adding Custom Options to your Joomla Template
In this guide, you will learn how to add custom fields/options to the Joomla template you designed. This guide assumes you already know the basics of Joomla…
Adding Custom Joomla Module Chrome (Styles)
Module Chromes are added by creating a new php file for each chrome/style under your template's directory at…
Creating Joomla Content Plugins (With Examples)
In this guide, you will learn the structure of a basic Joomla Content Plugin. We'll explore several examples, so you can create your own content plugins from…

Comments
Found an error? instead, it reaches me faster.No comments yet. Questions and corrections are welcome.