How to get user group id in Joomla 2.5.x

Thursday, August 30, 2012

How to get user group id in Joomla 2.5.x?

This tutorial will explain you how to get user group id in Joomla 2.5

Step 1 :

Create a function in factory.php (root_folder/libraries/joomla/factory.php)


public static function group_id($id = null)
{
if (is_null($id))
{
$instance = self::getSession()->get('user');
if (!($instance instanceof JUser))
{
$instance = JUser::getInstance();
}
}
else
{
$current = self::getSession()->get('user');
if ($current->id != $id)
{
$instance = JUser::getInstance($id);
}
else
{
$instance = self::getSession()->get('user');
}
}

jimport( 'joomla.access.access' );
$group_id = JAccess::getGroupsByUser($instance->id, false);

return $group_id[0];
}

Step 2:

Call group_id() function from your custom component or from anywhere by using the code below

<?php


$group_id = &JFactory::group_id();
echo 'User group id is '.$group_id ;


?>

You Might Also Like

3 comments

  1. Hi! It's really interesting.

    I have this piece of code:

    < ?php
    if(isset($this->cat_allow_submission) && $this->cat_allow_submission && $this->user_addlisting >= 0) {
    echo (whatever...);
    }
    (more code...)

    As you state in your article, I added 'step 1' in factory php. And now, in 'step 2', I have a doubt, how exactly adding the group_id condition? (I have a very, very, very little idea of coding, not at all an expert), maybe like this?

    < ?php
    $group_id = & JFactory::group_id();
    if (isset($this->cat_allow_submission) && $this->cat_allow_submission && $this->user_addlisting >= 0 && ($this->group_id == 8 | $this->group_id == 10)) {
    {
    echo (whatever...);
    }
    (more code...)

    Or am I doing something senseless?

    ReplyDelete
  2. Try this...

    cat_allow_submission) && $this->cat_allow_submission && $this->user_addlisting >= 0 && ($group_id == 8 || $group_id == 10)) {
    {
    echo (whatever...);
    }
    (more code...)

    I guess this solved your issue?

    ReplyDelete
  3. Yesssssss, sir!!!!! Thank you so much, buddy :)

    ReplyDelete