Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This function will build and return an array of all parent category id's that an article belongs to.
/**
* This function will build and return an array of all parent category id's that an article belongs to.
* Written by René Kreijveld, email [at] renekreijveld.nl
* 22-feb-2017
*
* Example function call for an article with id = 100:
* $parentCategories = $this->getCategories(100, 0);
*
*/
private function getCategories($artId, $catId)
{
$db = JFactory::getDBO();
// $catId = 0, so search the category of the article with id $artId.
if ($catId == 0)
{
$query = $db->getQuery(true)
->select($db->quoteName('catid'))
->from($db->quoteName('#__content'))
->where($db->quoteName('id') . ' = ' . (int) $artId);
$db->setQuery($query);
$parent = $db->loadResult();
$this->categories[] = $parent;
$this->getCategories(0, $parent);
}
// $artId = 0, so search the parent category of the category with id $catId.
if ($artId == 0)
{
$query = $db->getQuery(true)
->select($db->quoteName('parent_id'))
->from($db->quoteName('#__categories'))
->where($db->quoteName('id') . ' = ' . (int) $catId);
$db->setQuery($query);
$parent = $db->loadResult();
if ($parent != 1)
{
$this->categories[] = $parent;
$this->getCategories(0, $parent);
}
}
return $this->categories;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment