How can I create a Magento 2 category programmatically
You need to load Magento 2 CategoryFactory model first and then create a new Magento 2 category.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $categoryFactory = $objectManager->get('Magento\Catalog\Model\Category'); $rootNodeId = 1; //root category id $root = $categoryFactory->load($rootNodeId); $category = "New Category"; $name=ucfirst($category ); $url=strtolower($category ); $cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url)))))); $categoryTmp = $categoryFactory->create(); $categoryTmp->setName($name); $categoryTmp->setIsActive(true); $categoryTmp->setUrlKey($cleanurl); $categoryTmp->setData('description', 'description'); $categoryTmp->setParentId($rootNodeId); $mediaAttribute = array ('image', 'small_image', 'thumbnail'); $categoryTmp->setImage('/new.png', $mediaAttribute, true, false);// Path pub/meida/catalog/category/new.png $categoryTmp->setStoreId(1); $categoryTmp->setPath($root->getPath()); $categoryTmp->save();