How to Sort the categories alphabetically?
1 Answer
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...!!!
-
-
2
-
i want to Sort the categories alphabetically except last one how it will do? 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