How to create categories and sub categories programmatically in magento2?

Please anyone knows then explain me.

  • 2
    check link:magento.stackexchange.com/a/134916
    – akgola
    Oct 11 '17 at 11:48
  • Have you got any solution for create tree level categories. I am facing same issue. Let me know if you have got solution. Any help would be appreciated. Thanks. Jun 20 '19 at 9:56

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 = [

$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

  • I tried this code but it's not working......pg not working error was displayed.wt i can do this
    – Mahi M
    Oct 11 '17 at 13:21
  • what error you got.. ?? share how you implemented this code Oct 11 '17 at 14:07
  • I have created a php script in magento2 root directory and executed the file but its not working.
    – Mahi M
    Oct 12 '17 at 5:03
  • i will suggest you to create a new module and put the code in controller or add the code in some existing controller of some module that you have created Oct 12 '17 at 7:57
  • @magentonoob I have tried this code it's working fine for root level categories. But can't able to create tree level categories. Jun 20 '19 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.