Tuesday 9 September 2014

Magento- Show categories which containing active prodcuts in main navigation

if you override or subclass Mage_Catalog_Block_Navigation you can do this fairly quickly. Add the method _hasProducts as shown below, then you need to call this inside the renderCategoriesMenuHtml() and _renderCategoryMenuItemHtml() methods…


Need to add below method in app\code\core\Mage\Catalog\Block\Navigation.php extend this in your local
it should be app\code\local\Mage\Catalog\Block\Navigation.php


/**
* Check if a product has an active products
* @param int $category_id
* @return boolean
*/
private function _hasProducts( $category_id )
{
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('entity_id')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4);
/* @var $products Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection */
return ( $products->count() > 0 )  ? true : false;
}

and then modify the below 2 methods 


public function renderCategoriesMenuHtml($level = 0, $outermostItemClass = '', $childrenWrapClass = '')
    {
        $activeCategories = array();
        foreach ($this->getStoreCategories() as $child) {
            if ($child->getIsActive()&& $this->_hasProducts($child->getId())) {
                $activeCategories[] = $child;
            }
        }





 protected function _renderCategoryMenuItemHtml($category, $level = 0, $isLast = false, $isFirst = false,
        $isOutermost = false, $outermostItemClass = '', $childrenWrapClass = '', $noEventAttributes = false)
    {
        if (!$category->getIsActive()) {
            return '';
        }
        $html = array();

        // get all children
        if (Mage::helper('catalog/category_flat')->isEnabled()) {
            $children = (array)$category->getChildrenNodes();
            $childrenCount = count($children);
        } else {
            $children = $category->getChildren();
            $childrenCount = $children->count();
        }
        $hasChildren = ($children && $childrenCount);

        // select active children
        $activeChildren = array();
        foreach ($children as $child) {
            if ($child->getIsActive()&&  $this->_hasProducts($child->getId())) {
                $activeChildren[] = $child;
            }
        }


The green background code is added in above both methods


Any quires, please post below