Question

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.

Was it helpful?

Solution

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 />';
} 

OTHER TIPS

First, you need to create the block at the following location:

Vendor\Extension\Block\Getcategoryinfo.php

<?php
namespace Vendor\Extension\Block;

class Getcategoryinfo extends \Magento\Framework\View\Element\Template
{ 
    protected $_categoryCollectionFactory;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        array $data = []
    ) {
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        parent::__construct($context, $data);
    }

    public function getCategoryCollection() {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addIsActiveFilter(); 
        return $collection;
    }
}

Now call that block function into .phtml file like this:

// get the list of all categories
$categories = $block->getCategoryCollection(); 
foreach ($categories as $category) {
    echo $category->getName() .' '.$category->getId() . '<br />'; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top