Display product count of a category in main navigation

To display Product Count of a particular category in the main navigation, just include the following code in function _addCategoriesToMenu() of the observer file. The Observer file is located at appcodecoreMageCatalogModelObserver.php


$prodCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($category);
			$prodCount = $prodCollection->count();
			if($prodCount=='0')
			{
				$prodCounts = '';
			}
			else
			{
				$prodCounts = ' ('.$prodCount.')';
			}
			$categoryData = array(
                'name' => $category->getName().$prodCounts,
                'id' => $nodeId,
                'url' => Mage::helper('catalog/category')->getCategoryUrl($category),
                'is_active' => $this->_isActiveMenuCategory($category),
				'thumbnail' => Mage::getModel('catalog/category')->load($category->getId())->getThumbnail()
            );

so the output will be:


protected function _addCategoriesToMenu($categories, $parentCategoryNode, $menuBlock, $addTags = false)
    {
        $categoryModel = Mage::getModel('catalog/category');
        foreach ($categories as $category) {
            if (!$category->getIsActive()) {
                continue;
            }

            $nodeId = 'category-node-' . $category->getId();

            $categoryModel->setId($category->getId());
            if ($addTags) {
                $menuBlock->addModelTags($categoryModel);
            }

            $tree = $parentCategoryNode->getTree();
			$prodCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($category);
			$prodCount = $prodCollection->count();
			if($prodCount=='0')
			{
				$prodCounts = '';
			}
			else
			{
				$prodCounts = ' ('.$prodCount.')';
			}
			$categoryData = array(
                'name' => $category->getName().$prodCounts,
                'id' => $nodeId,
                'url' => Mage::helper('catalog/category')->getCategoryUrl($category),
                'is_active' => $this->_isActiveMenuCategory($category),
				'thumbnail' => Mage::getModel('catalog/category')->load($category->getId())->getThumbnail()
            );
            $categoryNode = new Varien_Data_Tree_Node($categoryData, 'id', $tree, $parentCategoryNode);
            $parentCategoryNode->addChild($categoryNode);

            $flatHelper = Mage::helper('catalog/category_flat');
            if ($flatHelper->isEnabled() && $flatHelper->isBuilt(true)) {
                $subcategories = (array)$category->getChildrenNodes();
            } else {
                $subcategories = $category->getChildren();
            }

            $this->_addCategoriesToMenu($subcategories, $categoryNode, $menuBlock, $addTags);
        }
    }

Leave a Reply