Skip to content

Instantly share code, notes, and snippets.

@renekreijveld
Last active February 22, 2017 16:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renekreijveld/3572be03115e7f98fe008bb0c7fdc818 to your computer and use it in GitHub Desktop.
Save renekreijveld/3572be03115e7f98fe008bb0c7fdc818 to your computer and use it in GitHub Desktop.
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