About: Categories
Root Categories
One question that comes up occasionally is about how to access the current/all root categories. A lot of store designs include horizontal tabs with the main categories, so it’s good to know how to get them.
Pretty much all that is requires is already there, it’s just a matter of knowing where to look. In this case the relevant file is themes/default/content/boxes/categories.php. Looking at the source you’ll find the line:
$tree = $zm_categories->getCategoryTree();
This will assign a tree like hierarchy of ZMCategory objects to $tree. In fact, it’s not really a tree as $tree will be an array of the - root categories. So a simple way of displaying all root categories would be:
foreach ($zm_categories->getCategoryTree() as $category) {
echo $category->getName()."<BR>";
}
The current root category
Another thing is to find out the current root category on a category or product page. There are at least two methods, depending on taste:
1) Looking at the crumbtrail
The crumbtrail contains all information needed. Since the first element is usually ‘Home’, it’s the second crumb element we are interested in:
$crumb = $zm_crumbtrail->getCrumb(1);
echo $crumb->getName()."<br>";
echo $crumb->getUrl()."<br>";
2) Using the category path included in the request
URLs pointing to category and product pages typically include a parameter denoting the category path. ZMRequest has a method getCategoryPathArray() that allows to access that information in a straightforward manner:
$cpath = $zm_request->getCategoryPathArray();
$category = $zm_categories->getCategoryForId($cpath[0]);
The logical second step is to lookup the category for the category id from the path. Please note that here we are looking at the first element (index = 0), as this is just the categroy path.
Again, displaying the name and creating a URL for the root category are as simple as:
echo $category->getName();
echo zm_href(FILENAME_DEFAULT, $category->getPath(), false);
