I would like to create categories programmatically in magento 2.

Please suggest me proper code for it.

I have try this code Link but not working properly . I have to create number of categories on one code with sub-categoties. like import export.


1 Answer 1

use \Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl= $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$state = $objectManager->get('\Magento\Framework\App\State');
/// Get Website ID
$websiteId = $storeManager->getWebsite()->getWebsiteId();
echo 'websiteId: '.$websiteId." ";

/// Get Store ID
$store = $storeManager->getStore();
$storeId = $store->getStoreId();
echo 'storeId: '.$storeId." ";

/// Get Root Category ID
$rootNodeId = $store->getRootCategoryId();
echo 'rootNodeId: '.$rootNodeId." ";
/// Get Root Category
$rootCat = $objectManager->get('Magento\Catalog\Model\Category');
$cat_info = $rootCat->load($rootNodeId);

$categorys=array('Levis','Wranglers','Basics'); // Category Names
foreach($categorys as $cat)

$cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
/// Add a new sub category under root category
$categoryTmp = $categoryFactory->create();
$categoryTmp->setData('description', 'description');
$mediaAttribute = array ('image', 'small_image', 'thumbnail');
$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);// Path pub/meida/catalog/category/m2.png

This will add add multiple category programmatically below to the root category of magento2

set category path and do the reindex and flush cache

For reference you can chk.



  • 3
    this ->save() method is deprecated, I think the way to go is to use repository instead. Apr 10, 2017 at 16:27
  • 1
    This worked only half for me. I needed to save the category so I can get the ID, and then set the "path" on the category using the new ID, then save again. In my case the "path" had an invalid value and was not visible in the category tree in Magento Admin. Setting the path by hand in a 2nd step worked fine.
    – Wouter
    Oct 25, 2018 at 13:33

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