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 }
  • Which bit of code is on line 56? Also, you should change != to !== – Lodder Oct 30 '14 at 9:48
  • tnx @Lodder // line 56 : $catid[$i]= $cat->parent_id; // doesn't work – Sh4msi Oct 30 '14 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 Oct 30 '14 at 15:50
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

  • tnx // only for 1 level //how get all level ? – Sh4msi Oct 30 '14 at 23:32
  • @Sh4msi - I've updated the where clause in my answer. Try now – Lodder Oct 30 '14 at 23:34
  • But it doesn't work. – Sh4msi Oct 31 '14 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 Oct 31 '14 at 0:14
  • Grateful // Please write – Sh4msi Oct 31 '14 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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