1

enter image description here

How to Sort the categories alphabetically?

2
  • please try my answer's code once. Jul 29, 2019 at 10:31
  • Yes its working Thanks :) Jul 29, 2019 at 10:58

1 Answer 1

0

Try below code

Using Construct Method

protected $_categoryCollectionFactory;

public function __construct(
    ...

    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,

    ...
) {
    ...

    $this->_categoryCollectionFactory = $categoryCollectionFactory;

    ...
}

public function getCategoryCollection() {
    $collection = $this->_categoryCollectionFactory->create();
    $collection->addAttributeToSelect('*')->addAttributeToSort('name','ASC');

    foreach ($collection as $category) {
        echo $category->getId() . '<br />';
        echo $category->getName() . '<br />';
        echo $category->getUrl() . '<br />';
    }

}

Using Object manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

// get the list of all categories
$categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryCollection->create();
$categories->addAttributeToSelect('*')->addAttributeToSort('name','ASC');

foreach ($categories as $category) {
    echo $category->getId() . '<br />';
    echo $category->getName() . '<br />';
    echo $category->getUrl() . '<br />';
}

I hope it will work...!!!

6
  • yes its working for me Thanks :) Jul 29, 2019 at 10:57
  • 2
    Please avoid direct use on object manager
    – Amit Bera
    Jul 29, 2019 at 11:00
  • i want to Sort the categories alphabetically except last one how it will do? Jul 29, 2019 at 11:08
  • last will be at same position. Jul 29, 2019 at 11:08
  • @JunaidAshfaq : if you find my answer is useful to you then please upvote the answer so it will help others people as well. Thanks :) Jul 30, 2019 at 5:36

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.