Magento 2 – Get List of All Category Names and IDs

category-treemagento2magento2.2

How can I get a list of all category names and their ID's from a store on Magento 2.2?

For example something like this

  • Clothes 2
  • Shirts 5
  • T-shirts 7
  • T-shirts 8
  • Shoes 10
  • Sport shoes 12

It can be in any format and displayed anywhere on the site as long as I can copy it as text. I will disable this functionality after, so I don't mind if it's a quick and dirty way as it's never going on the live site.

Basically I'm trying to find a way to get all product names and ID's without having to individually click through every item in the Magento category tree.

Best Answer

Using Object Manager

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
$categoryCollection = $objectManager-
  >get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
 $categories = $categoryCollection->create();
 $categories->addAttributeToSelect('*');

   foreach ($categories as $category) {

      echo $category->getName() . '<br />';
   }

  $categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
  $categories = $categoryHelper->getStoreCategories();

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