Tuesday 24 June 2014

Magento Sort Category(Navigation) By Name or Alphabatically.

To sort Top Menu Categories and its Sub-Categoiries alphabetically,

Copy app/code/core/Mage/Catalog/Block/Navigation.php to app/code/local/Mage/Catalog/Block/Navigation.php OR you can override the same file in your local

public function toLinearArray($collection)
{
        $array = array();
        foreach ($collection as $item) $array[] = $item;
        return $array;
}

protected function _sortCategoriesByName($cat1, $cat2)
{
       return strcasecmp($cat1->getName(), $cat2->getName());
}

In Navigation.php edit the function _renderCategoryMenuItemHtml(), add the following 2 lines before the code $hasChildren = ($children && $childrenCount);

$children = $this->toLinearArray($children);
usort($children, array($this, '_sortCategoriesByName'));

If you need to sort Parent Categories too, use below code before your foreach loop when you display category list

<?php $helper = Mage::helper('catalog/category') ?>
<?php $categories = $helper->getStoreCategories(); ?>
               
<?php $children = $this->toLinearArray($categories);
usort($children, array($this, '_sortCategoriesByName'));?>
   
<?php foreach ($children as $_category): ?>
<?php echo $this->drawItem($_category) ?>
<?php endforeach ?>

No comments:

Post a Comment