Magento themes and extensions

Display product count in top menu

Share

Magento categories marked as ‘Include in menu’ are added by  page_block_html_topmenu_gethtml_before event observer function addCatalogToTopmenuItems located in app/code/core/Mage/Catalog/Model/Observer.php. Lets overwrite it:

1
2
cp app/code/core/Mage/Catalog/Model/Observer.php \
app/code/local/Mage/Catalog/Model/Observer.php

edit the function _addCategoriesToMenu:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
protected function _addCategoriesToMenu(
$categories
, $parentCategoryNode)
{
foreach ($categories as $category) {
if (!$category->getIsActive()) {
continue;
}
$nodeId = 'category-node-' . $category->getId();
$tree = $parentCategoryNode->getTree();
$categoryData = array(
'name' => $category
->getName()
.'('.
Mage::getModel('catalog/category')
->load($category->getId())
->getRecursiveProductCount().')',
'id' => $nodeId,
'url' => Mage::helper('catalog/category')
->getCategoryUrl($category),
'is_active' => $this
->_isActiveMenuCategory($category)
);
.........

Recursive function getRecursiveProductCount we define in app/code/local/Mage/Catalog/Model/Category.php:

1
2
cp app/code/core/Mage/Catalog/Model/Observer.php \
app/code/local/Mage/Catalog/Model/Observer.php
1
2
3
4
5
6
7
8
9
10
11
12
public function getRecursiveProductCount()
{
$count = $this->getProductCount();
$children = $this->getAllChildren(true);
if(count($children) == 0) return $count;
foreach($children as $id){
if($id == $this->getId()) continue;
$count += Mage::getModel('catalog/category')
->load($id)->getRecursiveProductCount();
}
return $count;
}

Comments are closed.