Skip to main content

Create Categories and Sub Categories for Magento2 by segments and pathes

 

 


// Render Setup Wizard landing page
$objectManager = Bootstrap::create(BP, $_SERVER)->getObjectManager();
$om = $objectManager;
try {
    $om->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml');
} catch (\Exception $e) {
}
$rootCategoryId = 50;//


// Services
$storeManager      = $om->get(\Magento\Store\Model\StoreManagerInterface::class);
$categoryFactory   = $om->get(\Magento\Catalog\Api\Data\CategoryInterfaceFactory::class);
$categoryRepo      = $om->get(\Magento\Catalog\Api\CategoryRepositoryInterface::class);
$collectionFactory = $om->get(\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory::class);



// --- Paste your array here ---
$paths = [
    "Main Category",
    "Main Category/Horticulture",
    "Main Category/Horticulture/Containers",
    "Main Category/Horticulture/Containers/Harvesting",
    "Main Category/Agricultural crops",
    // ... paste the full array here ...
    "Main Category/Home Gardening/Seeding and Protection equipment"
];

// ---- END ARRAY ----

// Helpers
$getChildIdByName = function (int $parentId, string $name) use ($collectionFactory) {
    $c = $collectionFactory->create();
    $c->addAttributeToSelect(['name'])
        ->addAttributeToFilter('parent_id', $parentId)
        ->addAttributeToFilter('name', $name)
        ->setPageSize(1);
    $item = $c->getFirstItem();
    return $item && $item->getId() ? (int)$item->getId() : null;
};

$getOrCreate = function (int $parentId, string $name) use ($getChildIdByName, $categoryFactory, $categoryRepo) {
    if ($id = $getChildIdByName($parentId, $name)) {
        return $id;
    }
    $cat = $categoryFactory->create();
    $cat->setName($name);
    $cat->setParentId($parentId);
    $cat->setIsActive(1);
    $cat->setIncludeInMenu(1);
    $cat = $categoryRepo->save($cat);
    return (int)$cat->getId();
};

foreach (array_unique($paths) as $path) {
    if (stripos($path, 'Main Category') !== 0) {
        continue;
    }
    $segments = explode('/', $path);
    array_shift($segments); // skip "Main Category"
    if (!$segments) {
        continue;
    }
    $parentId = $rootCategoryId;
    foreach ($segments as $name) {
        $parentId = $getOrCreate($parentId, trim($name));
    }
}

echo "Categories created successfully.\n";

you can also get the categories array from this script from product export

 


$cat = [];

$path = "export_cataog.csv";
$fileContent = file_get_contents($path);

$lines = explode(PHP_EOL, $fileContent);
foreach ($lines as $line) {
    $catPaths = explode("Default Category", $line);
    foreach ($catPaths as $catpath) {
        $ccc =  trim("Main Category".$catpath,",");
        if(!in_array($ccc, $cat)) {
            $cat[] = $ccc;
        }
    }
}


$paths = $cat;

Tags