4

I've found the topic of how to create root category in magento 2, but only form Admin Panel. I've found how to create SUBcategories programmatically in Magento 2 magento 2 create categories programmatically . I've found how to do it in Magento 1.x Create Root Category in magento programatically

But how to create a root category in Magento 2??

Audiophile
  • 317
  • 4
  • 15

1 Answers1

2

I found this one very interesting, I'm going to show you solution in template. You can implement following code.

My store name is m4 replace it with yours:

<?php


use \Magento\Framework\App\Bootstrap;

include('/var/www/html/m4/app/bootstrap.php');
$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');
$state->setAreaCode('frontend');


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

/// Get Root Category ID
$rootNodeId = 1; //set it as 1.
/// Get Root Category
$rootCat = $objectManager->get('Magento\Catalog\Model\Category');
$cat_info = $rootCat->load($rootNodeId);

$myRoot='animeroot4'; // Category Names

$name=ucfirst($myRoot);
$url=strtolower($myRoot);
$cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
$categoryFactory=$objectManager->get('\Magento\Catalog\Model\CategoryFactory');
/// Add a new sub category under root category
$categoryTmp = $categoryFactory->create();
$categoryTmp->setName($name);
$categoryTmp->setIsActive(true);
$categoryTmp->setUrlKey($cleanurl);
$categoryTmp->setData('description', 'description');
$categoryTmp->setParentId($rootCat->getId()); 
$mediaAttribute = array ('image', 'small_image', 'thumbnail');
$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);// Path pub/meida/catalog/category/m2.png
$categoryTmp->setStoreId($storeId);  
$categoryTmp->setPath($rootCat->getPath());
$categoryTmp->save();

It is tested by me and works perfectly.

P S
  • 1,983
  • 4
  • 22
  • 41