Create category in magento2 programmatically
In this we are going to see how we can create category in Magento2 programmatically,
First we need to have the ObjectManager by this code
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
Then let us have array with some Categories names
$cats = [ "cat1","cat2" ];
Let us setup the Parent Id of the categories
$parent_id = 322;
After that we will going throw the arrays items to create those categories
foreach($cats as $cat) { $data = [ 'data' => [ "parent_id" => $parent_id, 'name' => $cat, "is_active" => true, "position" => 10, "include_in_menu" => false, ] ]; $category = $objectManager ->create('Magento\Catalog\Model\Category', $data); $repository = $objectManager->get(\Magento\Catalog\Api\CategoryRepositoryInterface::class); $result = $repository->save($category); }
Full code will be like this
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $cats = [ "cat1","cat2" ]; $parent_id = 322; foreach($cats as $cat) { $data = [ 'data' => [ "parent_id" => $parent_id, 'name' => $cat, "is_active" => true, "position" => 10, "include_in_menu" => false, ] ]; $category = $objectManager ->create('Magento\Catalog\Model\Category', $data); $repository = $objectManager->get(\Magento\Catalog\Api\CategoryRepositoryInterface::class); $result = $repository->save($category); }
I hope this code will help you thank you for reading this wiki