create category programmatically if not exist - magento 2












3















I have one custom table, that table have a column name category which contains the events category like entertainment, national events. Now I need to create category from the table?



note: create category itself enough, don't need to add any products.



I tried with create one category by object manager if the category not exist but it does not work.



    $parentCategory = $this->_objectManager
->create('MagentoCatalogModelCategory')
->load('115');
$category = $this->_objectManager
->create('MagentoCatalogModelCategory');
$cate=$category->getCollection()->addAttributeToFilter('name',$d["type"])
->getFirstItem();
if(!isset($cate))
{
$category->setPath($parentCategory->getPath())
->setParentId('115')
->setName($d["type"])
->setIsActive(true);
$category->save();
}


how to deal with automatically create category from table, if not exist already.



Thanks










share|improve this question





























    3















    I have one custom table, that table have a column name category which contains the events category like entertainment, national events. Now I need to create category from the table?



    note: create category itself enough, don't need to add any products.



    I tried with create one category by object manager if the category not exist but it does not work.



        $parentCategory = $this->_objectManager
    ->create('MagentoCatalogModelCategory')
    ->load('115');
    $category = $this->_objectManager
    ->create('MagentoCatalogModelCategory');
    $cate=$category->getCollection()->addAttributeToFilter('name',$d["type"])
    ->getFirstItem();
    if(!isset($cate))
    {
    $category->setPath($parentCategory->getPath())
    ->setParentId('115')
    ->setName($d["type"])
    ->setIsActive(true);
    $category->save();
    }


    how to deal with automatically create category from table, if not exist already.



    Thanks










    share|improve this question



























      3












      3








      3








      I have one custom table, that table have a column name category which contains the events category like entertainment, national events. Now I need to create category from the table?



      note: create category itself enough, don't need to add any products.



      I tried with create one category by object manager if the category not exist but it does not work.



          $parentCategory = $this->_objectManager
      ->create('MagentoCatalogModelCategory')
      ->load('115');
      $category = $this->_objectManager
      ->create('MagentoCatalogModelCategory');
      $cate=$category->getCollection()->addAttributeToFilter('name',$d["type"])
      ->getFirstItem();
      if(!isset($cate))
      {
      $category->setPath($parentCategory->getPath())
      ->setParentId('115')
      ->setName($d["type"])
      ->setIsActive(true);
      $category->save();
      }


      how to deal with automatically create category from table, if not exist already.



      Thanks










      share|improve this question
















      I have one custom table, that table have a column name category which contains the events category like entertainment, national events. Now I need to create category from the table?



      note: create category itself enough, don't need to add any products.



      I tried with create one category by object manager if the category not exist but it does not work.



          $parentCategory = $this->_objectManager
      ->create('MagentoCatalogModelCategory')
      ->load('115');
      $category = $this->_objectManager
      ->create('MagentoCatalogModelCategory');
      $cate=$category->getCollection()->addAttributeToFilter('name',$d["type"])
      ->getFirstItem();
      if(!isset($cate))
      {
      $category->setPath($parentCategory->getPath())
      ->setParentId('115')
      ->setName($d["type"])
      ->setIsActive(true);
      $category->save();
      }


      how to deal with automatically create category from table, if not exist already.



      Thanks







      magento2 category category-attribute






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 7 mins ago









      Himanshu

      812521




      812521










      asked May 9 '16 at 12:45









      Bilal UseanBilal Usean

      4,48923385




      4,48923385






















          5 Answers
          5






          active

          oldest

          votes


















          3














          We need to identify the id of category tree root. Then, we
          created an instance of the category, set its path, parent_id, name, etc.



          /**
          * Id of category tree root
          */
          $parentId = MagentoCatalogModelCategory::TREE_ROOT_ID;

          $parentCategory = $this->_objectManager
          ->create('MagentoCatalogModelCategory')
          ->load($parentId);
          $category = $this->_objectManager
          ->create('MagentoCatalogModelCategory');
          //Check exist category
          $cate = $category->getCollection()
          ->addAttributeToFilter('name','test')
          ->getFirstItem();

          if(!isset($cate->getId())) {
          $category->setPath($parentCategory->getPath())
          ->setParentId($parentId)
          ->setName('test')
          ->setIsActive(true);
          $category->save();
          }





          share|improve this answer


























          • great @Khoa. it is create category in admin but it is not get visible in frontend navigation menu. I could compare with existing category but no difference found, all settings are same. what can I do now?

            – Bilal Usean
            May 9 '16 at 14:15











          • We should try $category->setIncludeInMenu(1). We should take a look more detail here: vendor/magento/module-catalog/Setup/CategorySetup.php

            – Khoa TruongDinh
            May 9 '16 at 14:29











          • how to check if the category exist?

            – Bilal Usean
            May 9 '16 at 14:47











          • From your post here: magento.stackexchange.com/questions/114637/…. We can try !isset($cate->getId())

            – Khoa TruongDinh
            May 10 '16 at 5:45











          • thanks @Khoa please update your answer with category check it is useful to others

            – Bilal Usean
            May 10 '16 at 5:46



















          1














          it will help me to add create category programaticaly.



          // catagory name
          $cat_name = ucfirst($cat_val);
          $site_url = strtolower($cat_val);
          $clean_url = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($site_url))))));
          $category_factory=$objectManager->get('MagentoCatalogModelCategoryFactory');
          // Add a new sub category under root category
          $category_obj = $category_factory->create();
          $category_obj->setName($cat_name);
          $category_obj->setIsActive(true);
          $category_obj->setUrlKey($clean_url);
          $category_obj->setData('description', 'description');
          $category_obj->setParentId($root_cat_id->getId());
          $mediaAttribute = array ('image', 'small_image', 'thumbnail');
          $category_obj->setImage('/catagory_img.png', $mediaAttribute, true, false);
          // add image at Path of pub/meida/catalog/category/catagory_img.png
          // add store id
          $category_obj->setStoreId($store_Id);
          $category_obj->setPath($root_cat_id->getPath());
          // save category
          $category_obj->save();





          share|improve this answer

































            1














            Consider using the Factory pattern for this instead of the object manager (unless you're putting this function in a factory class itself)



            class MyClass 
            {

            protected $storeManager;

            protected $categoryFactory;

            public function __construct(
            MagentoStoreModelStoreManagerInterface $storeManager,
            MagentoCatalogModelCategoryFactory $categoryFactory
            ) {
            $this->storeManager = $storeManager;
            $this->categoryFactory = $categoryFactory;
            }

            public function fetchOrCreateProductCategory($categoryName)
            {
            // get the current stores root category
            $parentId = $this->storeManager->getStore()->getRootCategoryId();

            $parentCategory = $this->categoryFactory->create()->load($parentId);

            $category = $this->categoryFactory->create();
            $cate = $category->getCollection()
            ->addAttributeToFilter('name', $categoryName)
            ->getFirstItem();

            if (!$cate->getId()) {
            $category->setPath($parentCategory->getPath())
            ->setParentId($parentId)
            ->setName($categoryName)
            ->setIsActive(true);
            $category->save();
            }

            return $category;
            }





            share|improve this answer

































              0














              When working with names I think it's better to use like



              //Check exist category
              $cate = $category->getCollection()
              ->addAttributeToFilter('name',['like' => $value])
              ->getFirstItem();





              share|improve this answer



















              • 1





                thanks, but I think its not suitable for my requirement. for example I need to add "coffee" category if not exist, please assume already "coffee chocolate" category exist. now the point is your code give result of "coffee" category already exist. am I right?

                – Bilal Usean
                May 11 '16 at 12:48











              • No , that will only be true if you add % after $value.'%' LIKE 'coffe%' would return true on 'coffee chocolate'

                – Joachim Vanthuyne
                May 11 '16 at 12:54













              • OK, I will work on your answer afterthat I will comeback to you

                – Bilal Usean
                May 11 '16 at 12:57



















              0















              $categories = array(

              array(

              'name' => 'Homedfd Appliances fsdfsdfd',

              'parent' => 97,

              'child' => array(

              'Television',

              'AC & Coolers',

              'Refrigerator',

              'Microwave Oven',

              'Fans', 'Kitchen Appliances',

              'Other Appliances' )

              ),

              array(

              'name' => 'Compudfdter dsfd',

              'parent' => 97,

              'child' => array(

              'Monitor',

              'Hard Drive',

              'Printer',

              'Wireless & Networking',

              'Webcams',

              'Keyboard',

              'Mouse'

              )

              ),

              array(

              'name' => 'Groomsfding Products',

              'parent' => 97,

              'child' => array(

              'Trimmers & Shavers',

              'Hair Styling Tools'

              )

              ),

              array(

              'name' => 'Moddbile & Tabs',

              'parent' => 97,

              'child' => array()

              )

              );
              /** Calling to magento functionalities*/use MagentoFrameworkAppBootstrap;include('./app/bootstrap.php');
              $bootstrap = Bootstrap::create(BP, $_SERVER);
              $objectManager = $bootstrap->getObjectManager();
              $url = MagentoFrameworkAppObjectManager::getInstance();
              $storeManager = $url->get('MagentoStoreModelStoreManagerInterface');
              $mediaurl = $storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
              $state = $objectManager->get('MagentoFrameworkAppState');

              $state->setAreaCode('frontend');
              $websiteId = $storeManager->getWebsite()->getWebsiteId();
              $store = $storeManager->getStore();
              $storeId = $store->getStoreId();
              $rootNodeId = $store->getRootCategoryId();
              $categoryModel = $objectManager->get('MagentoCatalogModelCategory');
              $rootCategoryInfo = $categoryModel->load($rootNodeId);
              $outputFile = fopen('catCreateResult.txt', 'w');
              foreach($categories as $cat){
              $name=ucfirst($cat['name']);
              $url=strtolower($cat['name']);
              $cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
              $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
              /// Add a new sub category under root category
              $categoryTmp = $categoryFactory->create();
              $categoryTmp->setName($name);
              $categoryTmp->setIsActive(true);
              /* * If you want to include category description please ucomment below line
              * As well as include a key with description value in category array and provide it on here.
              */
              //$categoryTmp->setData('description', 'description');
              $categoryTmp->setParentId($cat['parent']);
              $mediaAttribute = array ('image', 'small_image', 'thumbnail');
              /* * You can also set an category image. */
              //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);
              // Path pub/meida/catalog/category/m2.png $categoryTmp->setStoreId($storeId);
              $parentCategoryInfo = $categoryModel->load($cat['parent']);
              $categoryTmp->setPath($parentCategoryInfo->getPath());
              $output = $categoryTmp->save();
              $newId = $output->getEntityId();
              if(count($cat['child']) > 0){
              foreach($cat['child'] as $sub_child){
              $name=ucfirst($sub_child);
              $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
              $categoryTmp = $categoryFactory->create();
              $categoryTmp->setName($name);
              $categoryTmp->setIsActive(true);
              $categoryTmp->setParentId($newId);
              $mediaAttribute = array ('image', 'small_image', 'thumbnail');
              //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false); // Path pub/meida/catalog/category/m2.png
              $categoryTmp->setStoreId($storeId);
              $parentCategoryInfo = $categoryModel->load($newId);
              $categoryTmp->setPath($parentCategoryInfo->getPath());
              $categoryTmp->save();
              }
              }
              }


              For More Description you may visit here.






              share|improve this answer























                Your Answer








                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "479"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f114560%2fcreate-category-programmatically-if-not-exist-magento-2%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                3














                We need to identify the id of category tree root. Then, we
                created an instance of the category, set its path, parent_id, name, etc.



                /**
                * Id of category tree root
                */
                $parentId = MagentoCatalogModelCategory::TREE_ROOT_ID;

                $parentCategory = $this->_objectManager
                ->create('MagentoCatalogModelCategory')
                ->load($parentId);
                $category = $this->_objectManager
                ->create('MagentoCatalogModelCategory');
                //Check exist category
                $cate = $category->getCollection()
                ->addAttributeToFilter('name','test')
                ->getFirstItem();

                if(!isset($cate->getId())) {
                $category->setPath($parentCategory->getPath())
                ->setParentId($parentId)
                ->setName('test')
                ->setIsActive(true);
                $category->save();
                }





                share|improve this answer


























                • great @Khoa. it is create category in admin but it is not get visible in frontend navigation menu. I could compare with existing category but no difference found, all settings are same. what can I do now?

                  – Bilal Usean
                  May 9 '16 at 14:15











                • We should try $category->setIncludeInMenu(1). We should take a look more detail here: vendor/magento/module-catalog/Setup/CategorySetup.php

                  – Khoa TruongDinh
                  May 9 '16 at 14:29











                • how to check if the category exist?

                  – Bilal Usean
                  May 9 '16 at 14:47











                • From your post here: magento.stackexchange.com/questions/114637/…. We can try !isset($cate->getId())

                  – Khoa TruongDinh
                  May 10 '16 at 5:45











                • thanks @Khoa please update your answer with category check it is useful to others

                  – Bilal Usean
                  May 10 '16 at 5:46
















                3














                We need to identify the id of category tree root. Then, we
                created an instance of the category, set its path, parent_id, name, etc.



                /**
                * Id of category tree root
                */
                $parentId = MagentoCatalogModelCategory::TREE_ROOT_ID;

                $parentCategory = $this->_objectManager
                ->create('MagentoCatalogModelCategory')
                ->load($parentId);
                $category = $this->_objectManager
                ->create('MagentoCatalogModelCategory');
                //Check exist category
                $cate = $category->getCollection()
                ->addAttributeToFilter('name','test')
                ->getFirstItem();

                if(!isset($cate->getId())) {
                $category->setPath($parentCategory->getPath())
                ->setParentId($parentId)
                ->setName('test')
                ->setIsActive(true);
                $category->save();
                }





                share|improve this answer


























                • great @Khoa. it is create category in admin but it is not get visible in frontend navigation menu. I could compare with existing category but no difference found, all settings are same. what can I do now?

                  – Bilal Usean
                  May 9 '16 at 14:15











                • We should try $category->setIncludeInMenu(1). We should take a look more detail here: vendor/magento/module-catalog/Setup/CategorySetup.php

                  – Khoa TruongDinh
                  May 9 '16 at 14:29











                • how to check if the category exist?

                  – Bilal Usean
                  May 9 '16 at 14:47











                • From your post here: magento.stackexchange.com/questions/114637/…. We can try !isset($cate->getId())

                  – Khoa TruongDinh
                  May 10 '16 at 5:45











                • thanks @Khoa please update your answer with category check it is useful to others

                  – Bilal Usean
                  May 10 '16 at 5:46














                3












                3








                3







                We need to identify the id of category tree root. Then, we
                created an instance of the category, set its path, parent_id, name, etc.



                /**
                * Id of category tree root
                */
                $parentId = MagentoCatalogModelCategory::TREE_ROOT_ID;

                $parentCategory = $this->_objectManager
                ->create('MagentoCatalogModelCategory')
                ->load($parentId);
                $category = $this->_objectManager
                ->create('MagentoCatalogModelCategory');
                //Check exist category
                $cate = $category->getCollection()
                ->addAttributeToFilter('name','test')
                ->getFirstItem();

                if(!isset($cate->getId())) {
                $category->setPath($parentCategory->getPath())
                ->setParentId($parentId)
                ->setName('test')
                ->setIsActive(true);
                $category->save();
                }





                share|improve this answer















                We need to identify the id of category tree root. Then, we
                created an instance of the category, set its path, parent_id, name, etc.



                /**
                * Id of category tree root
                */
                $parentId = MagentoCatalogModelCategory::TREE_ROOT_ID;

                $parentCategory = $this->_objectManager
                ->create('MagentoCatalogModelCategory')
                ->load($parentId);
                $category = $this->_objectManager
                ->create('MagentoCatalogModelCategory');
                //Check exist category
                $cate = $category->getCollection()
                ->addAttributeToFilter('name','test')
                ->getFirstItem();

                if(!isset($cate->getId())) {
                $category->setPath($parentCategory->getPath())
                ->setParentId($parentId)
                ->setName('test')
                ->setIsActive(true);
                $category->save();
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 10 '16 at 5:50

























                answered May 9 '16 at 13:29









                Khoa TruongDinhKhoa TruongDinh

                21k63984




                21k63984













                • great @Khoa. it is create category in admin but it is not get visible in frontend navigation menu. I could compare with existing category but no difference found, all settings are same. what can I do now?

                  – Bilal Usean
                  May 9 '16 at 14:15











                • We should try $category->setIncludeInMenu(1). We should take a look more detail here: vendor/magento/module-catalog/Setup/CategorySetup.php

                  – Khoa TruongDinh
                  May 9 '16 at 14:29











                • how to check if the category exist?

                  – Bilal Usean
                  May 9 '16 at 14:47











                • From your post here: magento.stackexchange.com/questions/114637/…. We can try !isset($cate->getId())

                  – Khoa TruongDinh
                  May 10 '16 at 5:45











                • thanks @Khoa please update your answer with category check it is useful to others

                  – Bilal Usean
                  May 10 '16 at 5:46



















                • great @Khoa. it is create category in admin but it is not get visible in frontend navigation menu. I could compare with existing category but no difference found, all settings are same. what can I do now?

                  – Bilal Usean
                  May 9 '16 at 14:15











                • We should try $category->setIncludeInMenu(1). We should take a look more detail here: vendor/magento/module-catalog/Setup/CategorySetup.php

                  – Khoa TruongDinh
                  May 9 '16 at 14:29











                • how to check if the category exist?

                  – Bilal Usean
                  May 9 '16 at 14:47











                • From your post here: magento.stackexchange.com/questions/114637/…. We can try !isset($cate->getId())

                  – Khoa TruongDinh
                  May 10 '16 at 5:45











                • thanks @Khoa please update your answer with category check it is useful to others

                  – Bilal Usean
                  May 10 '16 at 5:46

















                great @Khoa. it is create category in admin but it is not get visible in frontend navigation menu. I could compare with existing category but no difference found, all settings are same. what can I do now?

                – Bilal Usean
                May 9 '16 at 14:15





                great @Khoa. it is create category in admin but it is not get visible in frontend navigation menu. I could compare with existing category but no difference found, all settings are same. what can I do now?

                – Bilal Usean
                May 9 '16 at 14:15













                We should try $category->setIncludeInMenu(1). We should take a look more detail here: vendor/magento/module-catalog/Setup/CategorySetup.php

                – Khoa TruongDinh
                May 9 '16 at 14:29





                We should try $category->setIncludeInMenu(1). We should take a look more detail here: vendor/magento/module-catalog/Setup/CategorySetup.php

                – Khoa TruongDinh
                May 9 '16 at 14:29













                how to check if the category exist?

                – Bilal Usean
                May 9 '16 at 14:47





                how to check if the category exist?

                – Bilal Usean
                May 9 '16 at 14:47













                From your post here: magento.stackexchange.com/questions/114637/…. We can try !isset($cate->getId())

                – Khoa TruongDinh
                May 10 '16 at 5:45





                From your post here: magento.stackexchange.com/questions/114637/…. We can try !isset($cate->getId())

                – Khoa TruongDinh
                May 10 '16 at 5:45













                thanks @Khoa please update your answer with category check it is useful to others

                – Bilal Usean
                May 10 '16 at 5:46





                thanks @Khoa please update your answer with category check it is useful to others

                – Bilal Usean
                May 10 '16 at 5:46













                1














                it will help me to add create category programaticaly.



                // catagory name
                $cat_name = ucfirst($cat_val);
                $site_url = strtolower($cat_val);
                $clean_url = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($site_url))))));
                $category_factory=$objectManager->get('MagentoCatalogModelCategoryFactory');
                // Add a new sub category under root category
                $category_obj = $category_factory->create();
                $category_obj->setName($cat_name);
                $category_obj->setIsActive(true);
                $category_obj->setUrlKey($clean_url);
                $category_obj->setData('description', 'description');
                $category_obj->setParentId($root_cat_id->getId());
                $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                $category_obj->setImage('/catagory_img.png', $mediaAttribute, true, false);
                // add image at Path of pub/meida/catalog/category/catagory_img.png
                // add store id
                $category_obj->setStoreId($store_Id);
                $category_obj->setPath($root_cat_id->getPath());
                // save category
                $category_obj->save();





                share|improve this answer






























                  1














                  it will help me to add create category programaticaly.



                  // catagory name
                  $cat_name = ucfirst($cat_val);
                  $site_url = strtolower($cat_val);
                  $clean_url = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($site_url))))));
                  $category_factory=$objectManager->get('MagentoCatalogModelCategoryFactory');
                  // Add a new sub category under root category
                  $category_obj = $category_factory->create();
                  $category_obj->setName($cat_name);
                  $category_obj->setIsActive(true);
                  $category_obj->setUrlKey($clean_url);
                  $category_obj->setData('description', 'description');
                  $category_obj->setParentId($root_cat_id->getId());
                  $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                  $category_obj->setImage('/catagory_img.png', $mediaAttribute, true, false);
                  // add image at Path of pub/meida/catalog/category/catagory_img.png
                  // add store id
                  $category_obj->setStoreId($store_Id);
                  $category_obj->setPath($root_cat_id->getPath());
                  // save category
                  $category_obj->save();





                  share|improve this answer




























                    1












                    1








                    1







                    it will help me to add create category programaticaly.



                    // catagory name
                    $cat_name = ucfirst($cat_val);
                    $site_url = strtolower($cat_val);
                    $clean_url = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($site_url))))));
                    $category_factory=$objectManager->get('MagentoCatalogModelCategoryFactory');
                    // Add a new sub category under root category
                    $category_obj = $category_factory->create();
                    $category_obj->setName($cat_name);
                    $category_obj->setIsActive(true);
                    $category_obj->setUrlKey($clean_url);
                    $category_obj->setData('description', 'description');
                    $category_obj->setParentId($root_cat_id->getId());
                    $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                    $category_obj->setImage('/catagory_img.png', $mediaAttribute, true, false);
                    // add image at Path of pub/meida/catalog/category/catagory_img.png
                    // add store id
                    $category_obj->setStoreId($store_Id);
                    $category_obj->setPath($root_cat_id->getPath());
                    // save category
                    $category_obj->save();





                    share|improve this answer















                    it will help me to add create category programaticaly.



                    // catagory name
                    $cat_name = ucfirst($cat_val);
                    $site_url = strtolower($cat_val);
                    $clean_url = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($site_url))))));
                    $category_factory=$objectManager->get('MagentoCatalogModelCategoryFactory');
                    // Add a new sub category under root category
                    $category_obj = $category_factory->create();
                    $category_obj->setName($cat_name);
                    $category_obj->setIsActive(true);
                    $category_obj->setUrlKey($clean_url);
                    $category_obj->setData('description', 'description');
                    $category_obj->setParentId($root_cat_id->getId());
                    $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                    $category_obj->setImage('/catagory_img.png', $mediaAttribute, true, false);
                    // add image at Path of pub/meida/catalog/category/catagory_img.png
                    // add store id
                    $category_obj->setStoreId($store_Id);
                    $category_obj->setPath($root_cat_id->getPath());
                    // save category
                    $category_obj->save();






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jul 27 '17 at 21:17









                    Marius

                    164k28312663




                    164k28312663










                    answered Mar 6 '17 at 7:41









                    Dhaval DaveDhaval Dave

                    3561414




                    3561414























                        1














                        Consider using the Factory pattern for this instead of the object manager (unless you're putting this function in a factory class itself)



                        class MyClass 
                        {

                        protected $storeManager;

                        protected $categoryFactory;

                        public function __construct(
                        MagentoStoreModelStoreManagerInterface $storeManager,
                        MagentoCatalogModelCategoryFactory $categoryFactory
                        ) {
                        $this->storeManager = $storeManager;
                        $this->categoryFactory = $categoryFactory;
                        }

                        public function fetchOrCreateProductCategory($categoryName)
                        {
                        // get the current stores root category
                        $parentId = $this->storeManager->getStore()->getRootCategoryId();

                        $parentCategory = $this->categoryFactory->create()->load($parentId);

                        $category = $this->categoryFactory->create();
                        $cate = $category->getCollection()
                        ->addAttributeToFilter('name', $categoryName)
                        ->getFirstItem();

                        if (!$cate->getId()) {
                        $category->setPath($parentCategory->getPath())
                        ->setParentId($parentId)
                        ->setName($categoryName)
                        ->setIsActive(true);
                        $category->save();
                        }

                        return $category;
                        }





                        share|improve this answer






























                          1














                          Consider using the Factory pattern for this instead of the object manager (unless you're putting this function in a factory class itself)



                          class MyClass 
                          {

                          protected $storeManager;

                          protected $categoryFactory;

                          public function __construct(
                          MagentoStoreModelStoreManagerInterface $storeManager,
                          MagentoCatalogModelCategoryFactory $categoryFactory
                          ) {
                          $this->storeManager = $storeManager;
                          $this->categoryFactory = $categoryFactory;
                          }

                          public function fetchOrCreateProductCategory($categoryName)
                          {
                          // get the current stores root category
                          $parentId = $this->storeManager->getStore()->getRootCategoryId();

                          $parentCategory = $this->categoryFactory->create()->load($parentId);

                          $category = $this->categoryFactory->create();
                          $cate = $category->getCollection()
                          ->addAttributeToFilter('name', $categoryName)
                          ->getFirstItem();

                          if (!$cate->getId()) {
                          $category->setPath($parentCategory->getPath())
                          ->setParentId($parentId)
                          ->setName($categoryName)
                          ->setIsActive(true);
                          $category->save();
                          }

                          return $category;
                          }





                          share|improve this answer




























                            1












                            1








                            1







                            Consider using the Factory pattern for this instead of the object manager (unless you're putting this function in a factory class itself)



                            class MyClass 
                            {

                            protected $storeManager;

                            protected $categoryFactory;

                            public function __construct(
                            MagentoStoreModelStoreManagerInterface $storeManager,
                            MagentoCatalogModelCategoryFactory $categoryFactory
                            ) {
                            $this->storeManager = $storeManager;
                            $this->categoryFactory = $categoryFactory;
                            }

                            public function fetchOrCreateProductCategory($categoryName)
                            {
                            // get the current stores root category
                            $parentId = $this->storeManager->getStore()->getRootCategoryId();

                            $parentCategory = $this->categoryFactory->create()->load($parentId);

                            $category = $this->categoryFactory->create();
                            $cate = $category->getCollection()
                            ->addAttributeToFilter('name', $categoryName)
                            ->getFirstItem();

                            if (!$cate->getId()) {
                            $category->setPath($parentCategory->getPath())
                            ->setParentId($parentId)
                            ->setName($categoryName)
                            ->setIsActive(true);
                            $category->save();
                            }

                            return $category;
                            }





                            share|improve this answer















                            Consider using the Factory pattern for this instead of the object manager (unless you're putting this function in a factory class itself)



                            class MyClass 
                            {

                            protected $storeManager;

                            protected $categoryFactory;

                            public function __construct(
                            MagentoStoreModelStoreManagerInterface $storeManager,
                            MagentoCatalogModelCategoryFactory $categoryFactory
                            ) {
                            $this->storeManager = $storeManager;
                            $this->categoryFactory = $categoryFactory;
                            }

                            public function fetchOrCreateProductCategory($categoryName)
                            {
                            // get the current stores root category
                            $parentId = $this->storeManager->getStore()->getRootCategoryId();

                            $parentCategory = $this->categoryFactory->create()->load($parentId);

                            $category = $this->categoryFactory->create();
                            $cate = $category->getCollection()
                            ->addAttributeToFilter('name', $categoryName)
                            ->getFirstItem();

                            if (!$cate->getId()) {
                            $category->setPath($parentCategory->getPath())
                            ->setParentId($parentId)
                            ->setName($categoryName)
                            ->setIsActive(true);
                            $category->save();
                            }

                            return $category;
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Aug 17 '17 at 15:17

























                            answered Aug 17 '17 at 15:05









                            paul_gatherpaul_gather

                            112




                            112























                                0














                                When working with names I think it's better to use like



                                //Check exist category
                                $cate = $category->getCollection()
                                ->addAttributeToFilter('name',['like' => $value])
                                ->getFirstItem();





                                share|improve this answer



















                                • 1





                                  thanks, but I think its not suitable for my requirement. for example I need to add "coffee" category if not exist, please assume already "coffee chocolate" category exist. now the point is your code give result of "coffee" category already exist. am I right?

                                  – Bilal Usean
                                  May 11 '16 at 12:48











                                • No , that will only be true if you add % after $value.'%' LIKE 'coffe%' would return true on 'coffee chocolate'

                                  – Joachim Vanthuyne
                                  May 11 '16 at 12:54













                                • OK, I will work on your answer afterthat I will comeback to you

                                  – Bilal Usean
                                  May 11 '16 at 12:57
















                                0














                                When working with names I think it's better to use like



                                //Check exist category
                                $cate = $category->getCollection()
                                ->addAttributeToFilter('name',['like' => $value])
                                ->getFirstItem();





                                share|improve this answer



















                                • 1





                                  thanks, but I think its not suitable for my requirement. for example I need to add "coffee" category if not exist, please assume already "coffee chocolate" category exist. now the point is your code give result of "coffee" category already exist. am I right?

                                  – Bilal Usean
                                  May 11 '16 at 12:48











                                • No , that will only be true if you add % after $value.'%' LIKE 'coffe%' would return true on 'coffee chocolate'

                                  – Joachim Vanthuyne
                                  May 11 '16 at 12:54













                                • OK, I will work on your answer afterthat I will comeback to you

                                  – Bilal Usean
                                  May 11 '16 at 12:57














                                0












                                0








                                0







                                When working with names I think it's better to use like



                                //Check exist category
                                $cate = $category->getCollection()
                                ->addAttributeToFilter('name',['like' => $value])
                                ->getFirstItem();





                                share|improve this answer













                                When working with names I think it's better to use like



                                //Check exist category
                                $cate = $category->getCollection()
                                ->addAttributeToFilter('name',['like' => $value])
                                ->getFirstItem();






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered May 11 '16 at 12:22









                                Joachim VanthuyneJoachim Vanthuyne

                                146114




                                146114








                                • 1





                                  thanks, but I think its not suitable for my requirement. for example I need to add "coffee" category if not exist, please assume already "coffee chocolate" category exist. now the point is your code give result of "coffee" category already exist. am I right?

                                  – Bilal Usean
                                  May 11 '16 at 12:48











                                • No , that will only be true if you add % after $value.'%' LIKE 'coffe%' would return true on 'coffee chocolate'

                                  – Joachim Vanthuyne
                                  May 11 '16 at 12:54













                                • OK, I will work on your answer afterthat I will comeback to you

                                  – Bilal Usean
                                  May 11 '16 at 12:57














                                • 1





                                  thanks, but I think its not suitable for my requirement. for example I need to add "coffee" category if not exist, please assume already "coffee chocolate" category exist. now the point is your code give result of "coffee" category already exist. am I right?

                                  – Bilal Usean
                                  May 11 '16 at 12:48











                                • No , that will only be true if you add % after $value.'%' LIKE 'coffe%' would return true on 'coffee chocolate'

                                  – Joachim Vanthuyne
                                  May 11 '16 at 12:54













                                • OK, I will work on your answer afterthat I will comeback to you

                                  – Bilal Usean
                                  May 11 '16 at 12:57








                                1




                                1





                                thanks, but I think its not suitable for my requirement. for example I need to add "coffee" category if not exist, please assume already "coffee chocolate" category exist. now the point is your code give result of "coffee" category already exist. am I right?

                                – Bilal Usean
                                May 11 '16 at 12:48





                                thanks, but I think its not suitable for my requirement. for example I need to add "coffee" category if not exist, please assume already "coffee chocolate" category exist. now the point is your code give result of "coffee" category already exist. am I right?

                                – Bilal Usean
                                May 11 '16 at 12:48













                                No , that will only be true if you add % after $value.'%' LIKE 'coffe%' would return true on 'coffee chocolate'

                                – Joachim Vanthuyne
                                May 11 '16 at 12:54







                                No , that will only be true if you add % after $value.'%' LIKE 'coffe%' would return true on 'coffee chocolate'

                                – Joachim Vanthuyne
                                May 11 '16 at 12:54















                                OK, I will work on your answer afterthat I will comeback to you

                                – Bilal Usean
                                May 11 '16 at 12:57





                                OK, I will work on your answer afterthat I will comeback to you

                                – Bilal Usean
                                May 11 '16 at 12:57











                                0















                                $categories = array(

                                array(

                                'name' => 'Homedfd Appliances fsdfsdfd',

                                'parent' => 97,

                                'child' => array(

                                'Television',

                                'AC & Coolers',

                                'Refrigerator',

                                'Microwave Oven',

                                'Fans', 'Kitchen Appliances',

                                'Other Appliances' )

                                ),

                                array(

                                'name' => 'Compudfdter dsfd',

                                'parent' => 97,

                                'child' => array(

                                'Monitor',

                                'Hard Drive',

                                'Printer',

                                'Wireless & Networking',

                                'Webcams',

                                'Keyboard',

                                'Mouse'

                                )

                                ),

                                array(

                                'name' => 'Groomsfding Products',

                                'parent' => 97,

                                'child' => array(

                                'Trimmers & Shavers',

                                'Hair Styling Tools'

                                )

                                ),

                                array(

                                'name' => 'Moddbile & Tabs',

                                'parent' => 97,

                                'child' => array()

                                )

                                );
                                /** Calling to magento functionalities*/use MagentoFrameworkAppBootstrap;include('./app/bootstrap.php');
                                $bootstrap = Bootstrap::create(BP, $_SERVER);
                                $objectManager = $bootstrap->getObjectManager();
                                $url = MagentoFrameworkAppObjectManager::getInstance();
                                $storeManager = $url->get('MagentoStoreModelStoreManagerInterface');
                                $mediaurl = $storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
                                $state = $objectManager->get('MagentoFrameworkAppState');

                                $state->setAreaCode('frontend');
                                $websiteId = $storeManager->getWebsite()->getWebsiteId();
                                $store = $storeManager->getStore();
                                $storeId = $store->getStoreId();
                                $rootNodeId = $store->getRootCategoryId();
                                $categoryModel = $objectManager->get('MagentoCatalogModelCategory');
                                $rootCategoryInfo = $categoryModel->load($rootNodeId);
                                $outputFile = fopen('catCreateResult.txt', 'w');
                                foreach($categories as $cat){
                                $name=ucfirst($cat['name']);
                                $url=strtolower($cat['name']);
                                $cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
                                $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
                                /// Add a new sub category under root category
                                $categoryTmp = $categoryFactory->create();
                                $categoryTmp->setName($name);
                                $categoryTmp->setIsActive(true);
                                /* * If you want to include category description please ucomment below line
                                * As well as include a key with description value in category array and provide it on here.
                                */
                                //$categoryTmp->setData('description', 'description');
                                $categoryTmp->setParentId($cat['parent']);
                                $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                                /* * You can also set an category image. */
                                //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);
                                // Path pub/meida/catalog/category/m2.png $categoryTmp->setStoreId($storeId);
                                $parentCategoryInfo = $categoryModel->load($cat['parent']);
                                $categoryTmp->setPath($parentCategoryInfo->getPath());
                                $output = $categoryTmp->save();
                                $newId = $output->getEntityId();
                                if(count($cat['child']) > 0){
                                foreach($cat['child'] as $sub_child){
                                $name=ucfirst($sub_child);
                                $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
                                $categoryTmp = $categoryFactory->create();
                                $categoryTmp->setName($name);
                                $categoryTmp->setIsActive(true);
                                $categoryTmp->setParentId($newId);
                                $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                                //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false); // Path pub/meida/catalog/category/m2.png
                                $categoryTmp->setStoreId($storeId);
                                $parentCategoryInfo = $categoryModel->load($newId);
                                $categoryTmp->setPath($parentCategoryInfo->getPath());
                                $categoryTmp->save();
                                }
                                }
                                }


                                For More Description you may visit here.






                                share|improve this answer




























                                  0















                                  $categories = array(

                                  array(

                                  'name' => 'Homedfd Appliances fsdfsdfd',

                                  'parent' => 97,

                                  'child' => array(

                                  'Television',

                                  'AC & Coolers',

                                  'Refrigerator',

                                  'Microwave Oven',

                                  'Fans', 'Kitchen Appliances',

                                  'Other Appliances' )

                                  ),

                                  array(

                                  'name' => 'Compudfdter dsfd',

                                  'parent' => 97,

                                  'child' => array(

                                  'Monitor',

                                  'Hard Drive',

                                  'Printer',

                                  'Wireless & Networking',

                                  'Webcams',

                                  'Keyboard',

                                  'Mouse'

                                  )

                                  ),

                                  array(

                                  'name' => 'Groomsfding Products',

                                  'parent' => 97,

                                  'child' => array(

                                  'Trimmers & Shavers',

                                  'Hair Styling Tools'

                                  )

                                  ),

                                  array(

                                  'name' => 'Moddbile & Tabs',

                                  'parent' => 97,

                                  'child' => array()

                                  )

                                  );
                                  /** Calling to magento functionalities*/use MagentoFrameworkAppBootstrap;include('./app/bootstrap.php');
                                  $bootstrap = Bootstrap::create(BP, $_SERVER);
                                  $objectManager = $bootstrap->getObjectManager();
                                  $url = MagentoFrameworkAppObjectManager::getInstance();
                                  $storeManager = $url->get('MagentoStoreModelStoreManagerInterface');
                                  $mediaurl = $storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
                                  $state = $objectManager->get('MagentoFrameworkAppState');

                                  $state->setAreaCode('frontend');
                                  $websiteId = $storeManager->getWebsite()->getWebsiteId();
                                  $store = $storeManager->getStore();
                                  $storeId = $store->getStoreId();
                                  $rootNodeId = $store->getRootCategoryId();
                                  $categoryModel = $objectManager->get('MagentoCatalogModelCategory');
                                  $rootCategoryInfo = $categoryModel->load($rootNodeId);
                                  $outputFile = fopen('catCreateResult.txt', 'w');
                                  foreach($categories as $cat){
                                  $name=ucfirst($cat['name']);
                                  $url=strtolower($cat['name']);
                                  $cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
                                  $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
                                  /// Add a new sub category under root category
                                  $categoryTmp = $categoryFactory->create();
                                  $categoryTmp->setName($name);
                                  $categoryTmp->setIsActive(true);
                                  /* * If you want to include category description please ucomment below line
                                  * As well as include a key with description value in category array and provide it on here.
                                  */
                                  //$categoryTmp->setData('description', 'description');
                                  $categoryTmp->setParentId($cat['parent']);
                                  $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                                  /* * You can also set an category image. */
                                  //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);
                                  // Path pub/meida/catalog/category/m2.png $categoryTmp->setStoreId($storeId);
                                  $parentCategoryInfo = $categoryModel->load($cat['parent']);
                                  $categoryTmp->setPath($parentCategoryInfo->getPath());
                                  $output = $categoryTmp->save();
                                  $newId = $output->getEntityId();
                                  if(count($cat['child']) > 0){
                                  foreach($cat['child'] as $sub_child){
                                  $name=ucfirst($sub_child);
                                  $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
                                  $categoryTmp = $categoryFactory->create();
                                  $categoryTmp->setName($name);
                                  $categoryTmp->setIsActive(true);
                                  $categoryTmp->setParentId($newId);
                                  $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                                  //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false); // Path pub/meida/catalog/category/m2.png
                                  $categoryTmp->setStoreId($storeId);
                                  $parentCategoryInfo = $categoryModel->load($newId);
                                  $categoryTmp->setPath($parentCategoryInfo->getPath());
                                  $categoryTmp->save();
                                  }
                                  }
                                  }


                                  For More Description you may visit here.






                                  share|improve this answer


























                                    0












                                    0








                                    0








                                    $categories = array(

                                    array(

                                    'name' => 'Homedfd Appliances fsdfsdfd',

                                    'parent' => 97,

                                    'child' => array(

                                    'Television',

                                    'AC & Coolers',

                                    'Refrigerator',

                                    'Microwave Oven',

                                    'Fans', 'Kitchen Appliances',

                                    'Other Appliances' )

                                    ),

                                    array(

                                    'name' => 'Compudfdter dsfd',

                                    'parent' => 97,

                                    'child' => array(

                                    'Monitor',

                                    'Hard Drive',

                                    'Printer',

                                    'Wireless & Networking',

                                    'Webcams',

                                    'Keyboard',

                                    'Mouse'

                                    )

                                    ),

                                    array(

                                    'name' => 'Groomsfding Products',

                                    'parent' => 97,

                                    'child' => array(

                                    'Trimmers & Shavers',

                                    'Hair Styling Tools'

                                    )

                                    ),

                                    array(

                                    'name' => 'Moddbile & Tabs',

                                    'parent' => 97,

                                    'child' => array()

                                    )

                                    );
                                    /** Calling to magento functionalities*/use MagentoFrameworkAppBootstrap;include('./app/bootstrap.php');
                                    $bootstrap = Bootstrap::create(BP, $_SERVER);
                                    $objectManager = $bootstrap->getObjectManager();
                                    $url = MagentoFrameworkAppObjectManager::getInstance();
                                    $storeManager = $url->get('MagentoStoreModelStoreManagerInterface');
                                    $mediaurl = $storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
                                    $state = $objectManager->get('MagentoFrameworkAppState');

                                    $state->setAreaCode('frontend');
                                    $websiteId = $storeManager->getWebsite()->getWebsiteId();
                                    $store = $storeManager->getStore();
                                    $storeId = $store->getStoreId();
                                    $rootNodeId = $store->getRootCategoryId();
                                    $categoryModel = $objectManager->get('MagentoCatalogModelCategory');
                                    $rootCategoryInfo = $categoryModel->load($rootNodeId);
                                    $outputFile = fopen('catCreateResult.txt', 'w');
                                    foreach($categories as $cat){
                                    $name=ucfirst($cat['name']);
                                    $url=strtolower($cat['name']);
                                    $cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
                                    $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
                                    /// Add a new sub category under root category
                                    $categoryTmp = $categoryFactory->create();
                                    $categoryTmp->setName($name);
                                    $categoryTmp->setIsActive(true);
                                    /* * If you want to include category description please ucomment below line
                                    * As well as include a key with description value in category array and provide it on here.
                                    */
                                    //$categoryTmp->setData('description', 'description');
                                    $categoryTmp->setParentId($cat['parent']);
                                    $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                                    /* * You can also set an category image. */
                                    //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);
                                    // Path pub/meida/catalog/category/m2.png $categoryTmp->setStoreId($storeId);
                                    $parentCategoryInfo = $categoryModel->load($cat['parent']);
                                    $categoryTmp->setPath($parentCategoryInfo->getPath());
                                    $output = $categoryTmp->save();
                                    $newId = $output->getEntityId();
                                    if(count($cat['child']) > 0){
                                    foreach($cat['child'] as $sub_child){
                                    $name=ucfirst($sub_child);
                                    $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
                                    $categoryTmp = $categoryFactory->create();
                                    $categoryTmp->setName($name);
                                    $categoryTmp->setIsActive(true);
                                    $categoryTmp->setParentId($newId);
                                    $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                                    //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false); // Path pub/meida/catalog/category/m2.png
                                    $categoryTmp->setStoreId($storeId);
                                    $parentCategoryInfo = $categoryModel->load($newId);
                                    $categoryTmp->setPath($parentCategoryInfo->getPath());
                                    $categoryTmp->save();
                                    }
                                    }
                                    }


                                    For More Description you may visit here.






                                    share|improve this answer














                                    $categories = array(

                                    array(

                                    'name' => 'Homedfd Appliances fsdfsdfd',

                                    'parent' => 97,

                                    'child' => array(

                                    'Television',

                                    'AC & Coolers',

                                    'Refrigerator',

                                    'Microwave Oven',

                                    'Fans', 'Kitchen Appliances',

                                    'Other Appliances' )

                                    ),

                                    array(

                                    'name' => 'Compudfdter dsfd',

                                    'parent' => 97,

                                    'child' => array(

                                    'Monitor',

                                    'Hard Drive',

                                    'Printer',

                                    'Wireless & Networking',

                                    'Webcams',

                                    'Keyboard',

                                    'Mouse'

                                    )

                                    ),

                                    array(

                                    'name' => 'Groomsfding Products',

                                    'parent' => 97,

                                    'child' => array(

                                    'Trimmers & Shavers',

                                    'Hair Styling Tools'

                                    )

                                    ),

                                    array(

                                    'name' => 'Moddbile & Tabs',

                                    'parent' => 97,

                                    'child' => array()

                                    )

                                    );
                                    /** Calling to magento functionalities*/use MagentoFrameworkAppBootstrap;include('./app/bootstrap.php');
                                    $bootstrap = Bootstrap::create(BP, $_SERVER);
                                    $objectManager = $bootstrap->getObjectManager();
                                    $url = MagentoFrameworkAppObjectManager::getInstance();
                                    $storeManager = $url->get('MagentoStoreModelStoreManagerInterface');
                                    $mediaurl = $storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);
                                    $state = $objectManager->get('MagentoFrameworkAppState');

                                    $state->setAreaCode('frontend');
                                    $websiteId = $storeManager->getWebsite()->getWebsiteId();
                                    $store = $storeManager->getStore();
                                    $storeId = $store->getStoreId();
                                    $rootNodeId = $store->getRootCategoryId();
                                    $categoryModel = $objectManager->get('MagentoCatalogModelCategory');
                                    $rootCategoryInfo = $categoryModel->load($rootNodeId);
                                    $outputFile = fopen('catCreateResult.txt', 'w');
                                    foreach($categories as $cat){
                                    $name=ucfirst($cat['name']);
                                    $url=strtolower($cat['name']);
                                    $cleanurl = trim(preg_replace('/ +/', '', preg_replace('/[^A-Za-z0-9 ]/', '', urldecode(html_entity_decode(strip_tags($url))))));
                                    $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
                                    /// Add a new sub category under root category
                                    $categoryTmp = $categoryFactory->create();
                                    $categoryTmp->setName($name);
                                    $categoryTmp->setIsActive(true);
                                    /* * If you want to include category description please ucomment below line
                                    * As well as include a key with description value in category array and provide it on here.
                                    */
                                    //$categoryTmp->setData('description', 'description');
                                    $categoryTmp->setParentId($cat['parent']);
                                    $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                                    /* * You can also set an category image. */
                                    //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false);
                                    // Path pub/meida/catalog/category/m2.png $categoryTmp->setStoreId($storeId);
                                    $parentCategoryInfo = $categoryModel->load($cat['parent']);
                                    $categoryTmp->setPath($parentCategoryInfo->getPath());
                                    $output = $categoryTmp->save();
                                    $newId = $output->getEntityId();
                                    if(count($cat['child']) > 0){
                                    foreach($cat['child'] as $sub_child){
                                    $name=ucfirst($sub_child);
                                    $categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');
                                    $categoryTmp = $categoryFactory->create();
                                    $categoryTmp->setName($name);
                                    $categoryTmp->setIsActive(true);
                                    $categoryTmp->setParentId($newId);
                                    $mediaAttribute = array ('image', 'small_image', 'thumbnail');
                                    //$categoryTmp->setImage('/m2.png', $mediaAttribute, true, false); // Path pub/meida/catalog/category/m2.png
                                    $categoryTmp->setStoreId($storeId);
                                    $parentCategoryInfo = $categoryModel->load($newId);
                                    $categoryTmp->setPath($parentCategoryInfo->getPath());
                                    $categoryTmp->save();
                                    }
                                    }
                                    }


                                    For More Description you may visit here.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jul 27 '17 at 7:41









                                    DelwaRDelwaR

                                    261




                                    261






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Magento Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f114560%2fcreate-category-programmatically-if-not-exist-magento-2%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Polycentropodidae

                                        Magento 2 Error message: Invalid state change requested

                                        Paulmy