1

enter image description here

How to Sort the categories alphabetically?

2
  • please try my answer's code once. Commented Jul 29, 2019 at 10:31
  • Yes its working Thanks :) Commented 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 :) Commented Jul 29, 2019 at 10:57
  • 2
    Please avoid direct use on object manager
    – Amit Bera
    Commented Jul 29, 2019 at 11:00
  • i want to Sort the categories alphabetically except last one how it will do? Commented Jul 29, 2019 at 11:08
  • last will be at same position. Commented 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 :) Commented 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.