Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting categories in Magento according to the position in admin

Tags:

magento

I would like to know how to sort this list of categories (I followed this tutorial here http://www.devinrolsen.com/magento-custom-category-listing-block/) in magento by position in the admin panel? Currently it is sorted by id

<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildren();
$catIds = explode(',',$cats);
?>
<ul>
<?php foreach($catIds as $catId): ?>
    <li>
        <?php
            $category = Mage::getModel('catalog/category')->load($catId);
            echo '<a href="' . $category->getUrl() . '">';
            echo $category->getName() . '</a>';
        ?>
    </li>
<?php endforeach; ?>
</ul>
like image 686
james Avatar asked Apr 07 '11 18:04

james


3 Answers

If you want to sort the categories by the position created in adminhtml you can then, since catalog/category is an instance of Mage_Catalog_Model_Resource_Category_Collection, make a query where you specify what you want to select, filter and/or sort.

The case here is getting categories from catalog_category_entity select only the name, filtering after the id and sort the query on the position.

<?php 
 $subcategories = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('name')
->addFieldToFilter('parent_id', $categoryId)
->addAttributeToSort('position', ASC);
?>
like image 94
alex Avatar answered Nov 19 '22 13:11

alex


You're making way too much work for yourself trying to deal with IDs and stuff. The following is already sorted by position as standard.

<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
?>
<ul>
<?php foreach($cats as $category): ?>
    <li>
        <a href="<?php echo $category->getUrl() ?>"><?php echo $category->getName() ?></a>
    </li>
<?php endforeach; ?>
</ul>
like image 26
clockworkgeek Avatar answered Nov 19 '22 13:11

clockworkgeek


This is what I did:

$allCategories = Mage::getModel('catalog/category');
$CategoriesTree = $allCategories->getTreeModel()->load();
$categoriesIds = 
$CategoriesTree->getCollection()->addAttributeToSort('position', 'asc')->getAllIds();

after to retrieve the categories:

$categoryChildren = array();    

if ($categoriesIds) {
    foreach ($categoriesIds as $categoryId){
        $category = Mage::getModel('catalog/category')->load($categoryId);
        $categoryChildren[] = $category;
    }
}

and then:

// Sort by position
function comparePosition($a, $b) {
    if ($a->position == $b->position)
        return 0;
        return ($a->position > $b->position) ? 1 : -1;
    }

usort($categoryChildren, 'comparePosition');

Inverting the return (1 and -1) would obviously change the order. It worked just fine for me. Hope it helps someone.

like image 3
flextorh Avatar answered Nov 19 '22 11:11

flextorh