2

How to get all parent categories in joomla?

I've tried the following:

//get the Category Content Object 
jimport( 'joomla.application.categories' );
$categories = JCategories::getInstance('Content');

  $cid = urldecode(JRequest::getString('cid'));

  $i=0;
  $catid[$i] = $cid;

  while ($catid[$i] != "root") {

    $cat = $categories->get($catid[$i]);
    $i++;

    $catid[$i]= $cat->parent_id;

  }

  var_dump($catid);

But it doesn't work.

Notice: Trying to get property of non-object in E:\xamppppp\htdocs\**\**.php on line 56
array(2) { [0]=> string(2) "20" [1]=> NULL }
3
  • Which bit of code is on line 56? Also, you should change != to !==
    – Lodder
    Commented Oct 30, 2014 at 9:48
  • tnx @Lodder // line 56 : $catid[$i]= $cat->parent_id; // doesn't work
    – Sh4msi
    Commented Oct 30, 2014 at 9:58
  • Do you want to get (a) the parent category of a specific sub-category or (b) get all categories which have children or (c) the recursive process for part (a)?
    – Farahmand
    Commented Oct 30, 2014 at 15:50

1 Answer 1

1

The majority of the time, when I need to get data that is stored in the database, depending on the situation, I tend to stick to database queries as they are more flexible.

You could use the following:

$db = JFactory::getDbo();
$query = $db->getQuery(true);

$query->select($db->quoteName(array('title')))
      ->from($db->quoteName('#__categories'))
      ->where($db->quoteName('parent_id') . ' != 0')
      ->where($db->quoteName('extension') . ' = ' . $db->quote('com_content'));

$db->setQuery($query);
$rows = $db->loadObjectList();

foreach ($rows as $row) 
{
    echo '<p>' . $row->title . '</p>';
}

This will get all categories for com_content apart from the very root category.

I've added in a little foreach loop to display the title of the category for each result.

Hope this helps

7
  • tnx // only for 1 level //how get all level ?
    – Sh4msi
    Commented Oct 30, 2014 at 23:32
  • @Sh4msi - I've updated the where clause in my answer. Try now
    – Lodder
    Commented Oct 30, 2014 at 23:34
  • But it doesn't work.
    – Sh4msi
    Commented Oct 31, 2014 at 0:12
  • You're still using a while loop. Remove all your code and simply use the code I've provided you with, nothing else.
    – Lodder
    Commented Oct 31, 2014 at 0:14
  • Grateful // Please write
    – Sh4msi
    Commented Oct 31, 2014 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.