Magento – create categories and sub categories programmatically in magento2

categorymagento2PHP

How to create categories and sub categories programmatically in magento2?

Please anyone knows then explain me.

Best Answer

use following code to create category and subcategory. just make slight changes as per your requirement and use it where you want to create categories and sub categories

$objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
//you should prefer to use dependency injection here
$cats = [
    "cat1","cat2"
];

$parent_id = 322; // category id of parent
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);
}

credits: http://www.zexperto.com/magento2x/create-category-magento2-programmatically

Related Topic