1

enter image description here

How to Sort the categories alphabetically?

  • please try my answer's code once. – Balwant Singh Jul 29 at 10:31
  • Yes its working Thanks :) – Junaid Ashfaq Jul 29 at 10:58
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...!!!

  • yes its working for me Thanks :) – Junaid Ashfaq Jul 29 at 10:57
  • 2
    Please avoid direct use on object manager – Amit Bera Jul 29 at 11:00
  • i want to Sort the categories alphabetically except last one how it will do? – Junaid Ashfaq Jul 29 at 11:08
  • last will be at same position. – Junaid Ashfaq Jul 29 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 :) – Balwant Singh Jul 30 at 5:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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