Magento – How to list all parent categories

categorymagento-1.7

I'm trying to get all parent categories except root category from the collections returned using Mage::getModel('catalog/category');

My code :

$_category = Mage::getModel('catalog/category');    
    $_categories = $_category
                    ->getCollection()
                    ->addAttributeToSelect(array('name', 'image', 'description'));

    foreach ($_categories as $_category){
        print_r($_category);
        die(0);
        echo $_category->getName().'<>';

}

Output is :

Mage_Catalog_Model_Category Object (
    [_eventPrefix:protected] => catalog_category 
    [_eventObject:protected] => category 
    [_cacheTag:protected] => catalog_category 
    [_useFlatResource:protected] => 
    [_designAttributes:Mage_Catalog_Model_Category:private] => Array (
        [0] => custom_design 
        [1] => custom_design_from 
        [2] => custom_design_to 
        [3] => page_layout 
        [4] => custom_layout_update 
        [5] => custom_apply_to_products
    ) 
    [_treeModel:protected] => 
    [_defaultValues:protected] => Array () 
    [_storeValuesFlags:protected] => Array () 
    [_lockedAttributes:protected] => Array () 
    [_isDeleteable:protected] => 1 
    [_isReadonly:protected] => 
    [_resourceName:protected] => catalog/category 
    [_resource:protected] => 
    [_resourceCollectionName:protected] => catalog/category_collection 
    [_dataSaveAllowed:protected] => 1 
    [_isObjectNew:protected] => 
    [_data:protected] => Array (
        [entity_id] => 1 
        [entity_type_id] => 3 
        [attribute_set_id] => 0 
        [parent_id] => 0 
        [created_at] => 2013-09-14 12:39:35 
        [updated_at] => 2013-09-14 12:39:35 
        [path] => 1 
        [position] => 0 
        [level] => 0 
        [children_count] => 45 
        [name] => Root Catalog
    ) 
    [_hasDataChanges:protected] => 1 
    [_origData:protected] => Array (
        [entity_id] => 1 
        [entity_type_id] => 3 
        [attribute_set_id] => 0 
        [parent_id] => 0 
        [created_at] => 2013-09-14 12:39:35 
        [updated_at] => 2013-09-14 12:39:35 
        [path] => 1 
        [position] => 0 
        [level] => 0 
        [children_count] => 45 
        [name] => Root Catalog
    ) 
    [_idFieldName:protected] => entity_id 
    [_isDeleted:protected] => 
    [_oldFieldsMap:protected] => Array () 
    [_syncFieldsMap:protected] => Array ()
)

May be I need to add an extra attribute for this? Any other idea please share

Best Answer

This should get you the first level categories

$categories = Mage::getModel('catalog/category')->getCollection()
    ->addAttributeToSelect('*')//or you can just add some attributes
    ->addAttributeToFilter('level', 2)//2 is actually the first level
    ->addAttributeToFilter('is_active', 1)//if you want only active categories
;
Related Topic