A little background, I'm trying to do a custom Category listing, but at the moment it seems the Category not being sort as I seen on Admin.

Here's the code that I've done so far

        $current_store = $this->_storeManager->getStore();

        $root_category_id = $this->_storeManager->getStore()->getRootCategoryId();

        $collection = $this->_categoryCollectionFactory->create()
                    ->addAttributeToFilter('is_active', 1)

        return $collection->addAttributeToFilter('entity_id', array('nin' => $root_category_id))

And the result, when I tried to echo its ID is like below


But, from the Admin, it doesn't reflect the order correctly, below is the figure
enter image description here

The problem that I realize is, that, I have sub category, I tried to echo the query from above code, and then copy-paste it into sql GUI, and I realize, the position is kinda weird but, it does make-sense, because it's a sub category. Here's the result when I execute the query on sql GUI
enter image description here

So, what I tried to achieve is to sort above result, to reflecting what I set on Admin. Is there anything that I missed? I'm not sure where to look, since I've been stuck around 1-2 days, not sure what's the proper keyword, almost all keyword I did will arrive to product sort or kind of that, not category sort

Thanks in Advance!

2 Answers 2


For those who still needs some answer relating to this question, here's the answer

            $store_categories = $this->_categoryFactory->create();
            $store_categories = $store_categories->load($this->_root_category_id)->getChildrenCategories();

            foreach ($store_categories as $category) {

                //get id
                $category_id = $category->getId();

                //get category model
                $category = $this->getCategoryModel($category_id);

                $sub_children = $this->getActiveChildCategories($category);

                if (count($sub_children) > 0) {

                    $sub_categories = $this->getSubCategory($sub_children);
                    $categories = array_merge($categories, $sub_categories);

                } else {

                    $categories[] = $category;



The _categoryFactory comes from Magento\Catalog\Model\CategoryFactory.

It's pretty much covering what I want, but not really as I expected before, because I think it's not really efficient.

PS - I'm still new on Magento 2, so, if someone else has other answer that might be pretty much like I expect, then, I'm happily change it as Accepted Answer. :)



enter image description here Dạ THE BASIC STORE Open từ 10:00 đến 21:00 📮67 Nguyễn Thiện Thuật, P2, Quận 3 Hồ Chí Minh. Hi vọng bạn có thể đến thử. Có thanh toán thẻ bạn nhé.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.