Set Categories as attribute value model file

Set Categories as attribute value model file programmatically and sort the label using usort() function

<?php
class Addpeople_Categoryattr_Model_Attribute_Source_Type extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{


    public function getAllOptions()
    {
        $this->_options = array();
        $categories = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('id')
        ->addAttributeToSelect('name')
        ->addAttributeToFilter('level',2) 
        ->addAttributeToFilter('entity_id', array('nin' => 148)) //exclude manufacturers
        ->addIsActiveFilter();
        
        $this->_options[] = array (
                'label' => 'Select Category',
                'value' => '0'
            );
        
        foreach($categories as $category) {
            $this->_options[] = array (
                'label' => $category->getName(),
                'value' => $category->getId()
            );
        }
        usort($this->_options, array( $this,'sortByValue'));
        return $this->_options;
    }
    
    function sortByValue($a, $b) {
        return strnatcmp ( $a['label'],$b['label']);
    }
}

Share this Tutorial