Change sort order of Magento subcategories

2019-09-02 20:25发布

问题:

I am working on a site where I am displaying a list of all the subcategories associated with the current category. The code below works fine for that, but I'd like to change the way the list of subcategories is sorted. Currently, it sorts by category ID. I'd like it to show up in whatever order the Magento user put the categories in in the admin (where they can drag-and-drop to change the category order). Appreciate any help!

             <?php
                $currentCat = Mage::registry('current_category');

                if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
                {
                    // current category is a toplevel category
                    $loadCategory = $currentCat;
                }
                else
                {
                    // current category is a sub-(or subsub-, etc...)category of a toplevel category
                    // load the parent category of the current category
                    $loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
                }
                $subCategories = explode(',', $loadCategory->getChildren());

                foreach ( $subCategories as $subCategoryId )
                {
                    $cat = Mage::getModel('catalog/category')->load($subCategoryId);

                    if($cat->getIsActive())
                    {
                        echo '<a href="'.$cat->getURL().'">'.$cat->getName().'</a>';
                    }
                }
            ?>

回答1:

Try calling getChildrenCategories this will take into account the position of each category:

$loadCategory->getChildrenCategories()

EDITED

Unlike getChildren which returns a string of all category ids returns an array of Mage_Catalog_Model_Category so your code will need to be changed to take this into account.

From your code snippet above the following change should work. Note the call to getChildrenCategories() and the change in the foreach loop as each item should be a category object.

<?php
$currentCat = Mage::registry('current_category');

if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
{
    // current category is a toplevel category
    $loadCategory = $currentCat;
}
else
{
    // current category is a sub-(or subsub-, etc...)category of a toplevel category
    // load the parent category of the current category
    $loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
}
$subCategories = $loadCategory->getChildrenCategories();

foreach ( $subCategories as $subCategory )
{
    if($subCategory->getIsActive())
    {
        echo '<a href="'.$subCategory->getURL().'">'.$subCategory->getName().'</a>';
    }
}
?> 


标签: magento