Magento 2 Get category id using category title












10















I would like get category id by only using category title by using this kind of function.



->load($categoryTitle, 'title')
->getId();


Use case: Get category id by title and put id data to array in migration script.










share|improve this question





























    10















    I would like get category id by only using category title by using this kind of function.



    ->load($categoryTitle, 'title')
    ->getId();


    Use case: Get category id by title and put id data to array in migration script.










    share|improve this question



























      10












      10








      10


      2






      I would like get category id by only using category title by using this kind of function.



      ->load($categoryTitle, 'title')
      ->getId();


      Use case: Get category id by title and put id data to array in migration script.










      share|improve this question
















      I would like get category id by only using category title by using this kind of function.



      ->load($categoryTitle, 'title')
      ->getId();


      Use case: Get category id by title and put id data to array in migration script.







      magento2 category magento-2.0 filter category-attribute






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 12 '16 at 13:54







      kilis

















      asked May 12 '16 at 13:20









      kiliskilis

      1491214




      1491214






















          7 Answers
          7






          active

          oldest

          votes


















          14














          You can do it via collections:



          First you need to inject a CategoryFactory in your class constructor.



          Magento 2.0 & 2.1:



          public function __construct(
          ...
          MagentoCatalogModelCategoryFactory $categoryFactory
          ) {
          $this->_categoryFactory = $categoryFactory;
          parent::__construct(...);
          }


          Then anywhere else in your class you can do:



          $collection = $this->_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);

          if ($collection->getSize()) {
          $categoryId = $collection->getFirstItem()->getId();
          }


          Magento 2.2:



          public function __construct(
          ...
          MagentoCatalogModelResourceModelCategoryCollectionFactory $collecionFactory
          ) {
          $this->_collectionFactory = $collecionFactory;
          parent::__construct(...);
          }


          Then anywhere else in your class you can do:



          $collection = $this->collecionFactory
          ->create()
          ->addAttributeToFilter('name',$categoryTitle)
          ->setPageSize(1);

          if ($collection->getSize()) {
          $categoryId = $collection->getFirstItem()->getId();
          }





          share|improve this answer


























          • Got an error PHP Fatal error: Call to undefined method MagentoCatalogModelCategoryFactory::getCollection()

            – kilis
            May 12 '16 at 13:31






          • 1





            @kilis see my update, you need to use DI to inject that class ;)

            – Raphael at Digital Pianism
            May 12 '16 at 13:34











          • For my use case i need this kind of function $collection = $this->_objectManager->create('MagentoCatalogModelCategoryFactory') ->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

            – kilis
            May 12 '16 at 13:41






          • 1





            @kilis well it's bad practice to use the object manager directly, you should always use dependency injection

            – Raphael at Digital Pianism
            May 12 '16 at 13:42











          • yeah i know. Our project upgrade script is designed like that :/

            – kilis
            May 12 '16 at 13:43





















          3














          You can simple do it using name,



          $title = 'womens';
          $objectManager = MagentoFrameworkAppObjectManager::getInstance();
          $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name',$title);
          echo "<pre>";
          print_r($collection->getData());
          exit;





          share|improve this answer


























          • Not for FE use, upgrade script functionality needed.

            – kilis
            May 12 '16 at 13:53













          • you just have says title, i have updated my answer.

            – Rakesh Jesadiya
            May 18 '16 at 9:16



















          2














          Try Below Code For Phtml File:



          $objectManager = MagentoFrameworkAppObjectManager::getInstance();

          $_categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');

          $categoryTitle = 'Outdoor'; // Category Name

          $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name', ['in' => $categoryTitle]);

          if ($collection->getSize()) {
          $categoryId = $collection->getFirstItem()->getId();
          }





          share|improve this answer

































            2














            This can be done using service contracts which are considered as best practice.



            protected $categoryList;

            /**
            * @var SearchCriteriaBuilder
            */
            protected $searchCriteriaBuilder;

            /**
            * @var FilterBuilder
            */
            protected $filterBuilder;

            public function __construct(
            ------------
            CategoryListInterface $categoryList,
            SearchCriteriaBuilder $searchCriteriaBuilder,
            FilterBuilder $filterBuilder,
            -----------------
            )
            {
            $this->categoryList = $categoryList;
            $this->searchCriteriaBuilder = $searchCriteriaBuilder;
            $this->filterBuilder = $filterBuilder;
            parent::__construct(----------);
            }

            public function getNameCategory()
            {
            $enableFilter = $this->filterBuilder
            ->setField(MagentoCatalogModelCategory::KEY_NAME)
            ->setConditionType('like')
            ->setValue(self::CATEGORY_NAME_HELP) // name of the categroy on const
            ->create();


            $searchCriteria = $this->searchCriteriaBuilder
            ->addFilters($enableFilter)
            ->create();

            $items = $this->categoryList->getList($searchCriteria)->getItems();

            if(count($items) == 0)
            {
            return FALSE;
            }

            foreach ($items as $helpCategory)
            {
            $CategoryId = $helpCategory->getId()
            }
            return $CategoryId;
            }





            share|improve this answer
























            • +1 For best practice part

              – Akif
              Dec 22 '18 at 22:28



















            1














            I got it with help from my collage



            $this->_objectManager->get('MagentoCatalogModelCategoryFactory')->create()->getCollection()
            ->addFieldToSelect('name')
            ->addFieldToFilter('name', ['in' => $categoryTitle]);


            :)
            Since the collection will only return the record you want you can grab the only result with ->getFirstItem() on the above code






            share|improve this answer

































              0














              To refactor that in a functioning script i suggest using the following



              $obj = $bootstrap->getObjectManager();
              $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
              $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

              if ($collection->getSize()) {
              $categoryId = $collection->getFirstItem()->getCategoryId();
              }


              Edit:
              I made and tested a script. I created a file in /scripts/file.php



              <?php
              use MagentoFrameworkAppBootstrap;
              require __DIR__ . '/../app/bootstrap.php';

              $bootstrap = Bootstrap::create(BP, $_SERVER);

              $obj = $bootstrap->getObjectManager();

              // Set the state (not sure if this is neccessary)
              $obj = $bootstrap->getObjectManager();
              $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
              $categoryTitle = 'Test';
              $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);
              if ($collection->getSize()) {
              $categoryId = $collection->getFirstItem()->getId();
              echo $categoryId;
              }





              share|improve this answer


























              • Tried your code , but changed first line to $obj = $this->_objectManager; Got an [MagentoFrameworkExceptionLocalizedException] Invalid attribute name: title error

                – kilis
                May 12 '16 at 13:36













              • When you got that error you did not use my script.

                – Kay Int Veen
                May 12 '16 at 14:04











              • I just added a fully tested script. please check that. it will work for sure!

                – Kay Int Veen
                May 12 '16 at 14:09



















              0














              I managed to write my own (more efficient) method:



              $entityTypeId = MagentoCatalogSetupCategorySetup::CATEGORY_ENTITY_TYPE_ID;
              $row = $this->queryF("SELECT * FROM `eav_attribute` WHERE `entity_type_id` = $entityTypeId AND `attribute_code` = 'name'", 1);
              $nameAttributeId = $row['attribute_id'];
              $categoryNames = $this->queryF("SELECT * FROM `catalog_category_entity_varchar` WHERE `attribute_id` = '$nameAttributeId'");
              $this->categoryNameIdMap = ;
              foreach ($categoryNames as $item) {
              $id = $item['entity_id'];
              $title = $item['value'];
              $this->categoryNameIdMap[$title] = $id;
              }


              This code caches all title:ids into an array, and only query 2 times.



              Worked for me. Easier to use!






              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%2f115118%2fmagento-2-get-category-id-using-category-title%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                7 Answers
                7






                active

                oldest

                votes








                7 Answers
                7






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                14














                You can do it via collections:



                First you need to inject a CategoryFactory in your class constructor.



                Magento 2.0 & 2.1:



                public function __construct(
                ...
                MagentoCatalogModelCategoryFactory $categoryFactory
                ) {
                $this->_categoryFactory = $categoryFactory;
                parent::__construct(...);
                }


                Then anywhere else in your class you can do:



                $collection = $this->_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }


                Magento 2.2:



                public function __construct(
                ...
                MagentoCatalogModelResourceModelCategoryCollectionFactory $collecionFactory
                ) {
                $this->_collectionFactory = $collecionFactory;
                parent::__construct(...);
                }


                Then anywhere else in your class you can do:



                $collection = $this->collecionFactory
                ->create()
                ->addAttributeToFilter('name',$categoryTitle)
                ->setPageSize(1);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }





                share|improve this answer


























                • Got an error PHP Fatal error: Call to undefined method MagentoCatalogModelCategoryFactory::getCollection()

                  – kilis
                  May 12 '16 at 13:31






                • 1





                  @kilis see my update, you need to use DI to inject that class ;)

                  – Raphael at Digital Pianism
                  May 12 '16 at 13:34











                • For my use case i need this kind of function $collection = $this->_objectManager->create('MagentoCatalogModelCategoryFactory') ->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                  – kilis
                  May 12 '16 at 13:41






                • 1





                  @kilis well it's bad practice to use the object manager directly, you should always use dependency injection

                  – Raphael at Digital Pianism
                  May 12 '16 at 13:42











                • yeah i know. Our project upgrade script is designed like that :/

                  – kilis
                  May 12 '16 at 13:43


















                14














                You can do it via collections:



                First you need to inject a CategoryFactory in your class constructor.



                Magento 2.0 & 2.1:



                public function __construct(
                ...
                MagentoCatalogModelCategoryFactory $categoryFactory
                ) {
                $this->_categoryFactory = $categoryFactory;
                parent::__construct(...);
                }


                Then anywhere else in your class you can do:



                $collection = $this->_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }


                Magento 2.2:



                public function __construct(
                ...
                MagentoCatalogModelResourceModelCategoryCollectionFactory $collecionFactory
                ) {
                $this->_collectionFactory = $collecionFactory;
                parent::__construct(...);
                }


                Then anywhere else in your class you can do:



                $collection = $this->collecionFactory
                ->create()
                ->addAttributeToFilter('name',$categoryTitle)
                ->setPageSize(1);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }





                share|improve this answer


























                • Got an error PHP Fatal error: Call to undefined method MagentoCatalogModelCategoryFactory::getCollection()

                  – kilis
                  May 12 '16 at 13:31






                • 1





                  @kilis see my update, you need to use DI to inject that class ;)

                  – Raphael at Digital Pianism
                  May 12 '16 at 13:34











                • For my use case i need this kind of function $collection = $this->_objectManager->create('MagentoCatalogModelCategoryFactory') ->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                  – kilis
                  May 12 '16 at 13:41






                • 1





                  @kilis well it's bad practice to use the object manager directly, you should always use dependency injection

                  – Raphael at Digital Pianism
                  May 12 '16 at 13:42











                • yeah i know. Our project upgrade script is designed like that :/

                  – kilis
                  May 12 '16 at 13:43
















                14












                14








                14







                You can do it via collections:



                First you need to inject a CategoryFactory in your class constructor.



                Magento 2.0 & 2.1:



                public function __construct(
                ...
                MagentoCatalogModelCategoryFactory $categoryFactory
                ) {
                $this->_categoryFactory = $categoryFactory;
                parent::__construct(...);
                }


                Then anywhere else in your class you can do:



                $collection = $this->_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }


                Magento 2.2:



                public function __construct(
                ...
                MagentoCatalogModelResourceModelCategoryCollectionFactory $collecionFactory
                ) {
                $this->_collectionFactory = $collecionFactory;
                parent::__construct(...);
                }


                Then anywhere else in your class you can do:



                $collection = $this->collecionFactory
                ->create()
                ->addAttributeToFilter('name',$categoryTitle)
                ->setPageSize(1);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }





                share|improve this answer















                You can do it via collections:



                First you need to inject a CategoryFactory in your class constructor.



                Magento 2.0 & 2.1:



                public function __construct(
                ...
                MagentoCatalogModelCategoryFactory $categoryFactory
                ) {
                $this->_categoryFactory = $categoryFactory;
                parent::__construct(...);
                }


                Then anywhere else in your class you can do:



                $collection = $this->_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }


                Magento 2.2:



                public function __construct(
                ...
                MagentoCatalogModelResourceModelCategoryCollectionFactory $collecionFactory
                ) {
                $this->_collectionFactory = $collecionFactory;
                parent::__construct(...);
                }


                Then anywhere else in your class you can do:



                $collection = $this->collecionFactory
                ->create()
                ->addAttributeToFilter('name',$categoryTitle)
                ->setPageSize(1);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 14 '17 at 15:55









                Roger Getnoticed

                367




                367










                answered May 12 '16 at 13:24









                Raphael at Digital PianismRaphael at Digital Pianism

                53.5k19112270




                53.5k19112270













                • Got an error PHP Fatal error: Call to undefined method MagentoCatalogModelCategoryFactory::getCollection()

                  – kilis
                  May 12 '16 at 13:31






                • 1





                  @kilis see my update, you need to use DI to inject that class ;)

                  – Raphael at Digital Pianism
                  May 12 '16 at 13:34











                • For my use case i need this kind of function $collection = $this->_objectManager->create('MagentoCatalogModelCategoryFactory') ->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                  – kilis
                  May 12 '16 at 13:41






                • 1





                  @kilis well it's bad practice to use the object manager directly, you should always use dependency injection

                  – Raphael at Digital Pianism
                  May 12 '16 at 13:42











                • yeah i know. Our project upgrade script is designed like that :/

                  – kilis
                  May 12 '16 at 13:43





















                • Got an error PHP Fatal error: Call to undefined method MagentoCatalogModelCategoryFactory::getCollection()

                  – kilis
                  May 12 '16 at 13:31






                • 1





                  @kilis see my update, you need to use DI to inject that class ;)

                  – Raphael at Digital Pianism
                  May 12 '16 at 13:34











                • For my use case i need this kind of function $collection = $this->_objectManager->create('MagentoCatalogModelCategoryFactory') ->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                  – kilis
                  May 12 '16 at 13:41






                • 1





                  @kilis well it's bad practice to use the object manager directly, you should always use dependency injection

                  – Raphael at Digital Pianism
                  May 12 '16 at 13:42











                • yeah i know. Our project upgrade script is designed like that :/

                  – kilis
                  May 12 '16 at 13:43



















                Got an error PHP Fatal error: Call to undefined method MagentoCatalogModelCategoryFactory::getCollection()

                – kilis
                May 12 '16 at 13:31





                Got an error PHP Fatal error: Call to undefined method MagentoCatalogModelCategoryFactory::getCollection()

                – kilis
                May 12 '16 at 13:31




                1




                1





                @kilis see my update, you need to use DI to inject that class ;)

                – Raphael at Digital Pianism
                May 12 '16 at 13:34





                @kilis see my update, you need to use DI to inject that class ;)

                – Raphael at Digital Pianism
                May 12 '16 at 13:34













                For my use case i need this kind of function $collection = $this->_objectManager->create('MagentoCatalogModelCategoryFactory') ->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                – kilis
                May 12 '16 at 13:41





                For my use case i need this kind of function $collection = $this->_objectManager->create('MagentoCatalogModelCategoryFactory') ->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                – kilis
                May 12 '16 at 13:41




                1




                1





                @kilis well it's bad practice to use the object manager directly, you should always use dependency injection

                – Raphael at Digital Pianism
                May 12 '16 at 13:42





                @kilis well it's bad practice to use the object manager directly, you should always use dependency injection

                – Raphael at Digital Pianism
                May 12 '16 at 13:42













                yeah i know. Our project upgrade script is designed like that :/

                – kilis
                May 12 '16 at 13:43







                yeah i know. Our project upgrade script is designed like that :/

                – kilis
                May 12 '16 at 13:43















                3














                You can simple do it using name,



                $title = 'womens';
                $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name',$title);
                echo "<pre>";
                print_r($collection->getData());
                exit;





                share|improve this answer


























                • Not for FE use, upgrade script functionality needed.

                  – kilis
                  May 12 '16 at 13:53













                • you just have says title, i have updated my answer.

                  – Rakesh Jesadiya
                  May 18 '16 at 9:16
















                3














                You can simple do it using name,



                $title = 'womens';
                $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name',$title);
                echo "<pre>";
                print_r($collection->getData());
                exit;





                share|improve this answer


























                • Not for FE use, upgrade script functionality needed.

                  – kilis
                  May 12 '16 at 13:53













                • you just have says title, i have updated my answer.

                  – Rakesh Jesadiya
                  May 18 '16 at 9:16














                3












                3








                3







                You can simple do it using name,



                $title = 'womens';
                $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name',$title);
                echo "<pre>";
                print_r($collection->getData());
                exit;





                share|improve this answer















                You can simple do it using name,



                $title = 'womens';
                $objectManager = MagentoFrameworkAppObjectManager::getInstance();
                $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name',$title);
                echo "<pre>";
                print_r($collection->getData());
                exit;






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 14 '17 at 16:05









                Abhishek Panchal

                3,4233929




                3,4233929










                answered May 12 '16 at 13:49









                Rakesh JesadiyaRakesh Jesadiya

                28.7k1571119




                28.7k1571119













                • Not for FE use, upgrade script functionality needed.

                  – kilis
                  May 12 '16 at 13:53













                • you just have says title, i have updated my answer.

                  – Rakesh Jesadiya
                  May 18 '16 at 9:16



















                • Not for FE use, upgrade script functionality needed.

                  – kilis
                  May 12 '16 at 13:53













                • you just have says title, i have updated my answer.

                  – Rakesh Jesadiya
                  May 18 '16 at 9:16

















                Not for FE use, upgrade script functionality needed.

                – kilis
                May 12 '16 at 13:53







                Not for FE use, upgrade script functionality needed.

                – kilis
                May 12 '16 at 13:53















                you just have says title, i have updated my answer.

                – Rakesh Jesadiya
                May 18 '16 at 9:16





                you just have says title, i have updated my answer.

                – Rakesh Jesadiya
                May 18 '16 at 9:16











                2














                Try Below Code For Phtml File:



                $objectManager = MagentoFrameworkAppObjectManager::getInstance();

                $_categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');

                $categoryTitle = 'Outdoor'; // Category Name

                $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name', ['in' => $categoryTitle]);

                if ($collection->getSize()) {
                $categoryId = $collection->getFirstItem()->getId();
                }





                share|improve this answer






























                  2














                  Try Below Code For Phtml File:



                  $objectManager = MagentoFrameworkAppObjectManager::getInstance();

                  $_categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');

                  $categoryTitle = 'Outdoor'; // Category Name

                  $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name', ['in' => $categoryTitle]);

                  if ($collection->getSize()) {
                  $categoryId = $collection->getFirstItem()->getId();
                  }





                  share|improve this answer




























                    2












                    2








                    2







                    Try Below Code For Phtml File:



                    $objectManager = MagentoFrameworkAppObjectManager::getInstance();

                    $_categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');

                    $categoryTitle = 'Outdoor'; // Category Name

                    $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name', ['in' => $categoryTitle]);

                    if ($collection->getSize()) {
                    $categoryId = $collection->getFirstItem()->getId();
                    }





                    share|improve this answer















                    Try Below Code For Phtml File:



                    $objectManager = MagentoFrameworkAppObjectManager::getInstance();

                    $_categoryFactory = $objectManager->get('MagentoCatalogModelCategoryFactory');

                    $categoryTitle = 'Outdoor'; // Category Name

                    $collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name', ['in' => $categoryTitle]);

                    if ($collection->getSize()) {
                    $categoryId = $collection->getFirstItem()->getId();
                    }






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 19 '18 at 6:31









                    Haritha

                    376111




                    376111










                    answered Jun 19 '18 at 6:26









                    Govind Ram BhattGovind Ram Bhatt

                    235




                    235























                        2














                        This can be done using service contracts which are considered as best practice.



                        protected $categoryList;

                        /**
                        * @var SearchCriteriaBuilder
                        */
                        protected $searchCriteriaBuilder;

                        /**
                        * @var FilterBuilder
                        */
                        protected $filterBuilder;

                        public function __construct(
                        ------------
                        CategoryListInterface $categoryList,
                        SearchCriteriaBuilder $searchCriteriaBuilder,
                        FilterBuilder $filterBuilder,
                        -----------------
                        )
                        {
                        $this->categoryList = $categoryList;
                        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
                        $this->filterBuilder = $filterBuilder;
                        parent::__construct(----------);
                        }

                        public function getNameCategory()
                        {
                        $enableFilter = $this->filterBuilder
                        ->setField(MagentoCatalogModelCategory::KEY_NAME)
                        ->setConditionType('like')
                        ->setValue(self::CATEGORY_NAME_HELP) // name of the categroy on const
                        ->create();


                        $searchCriteria = $this->searchCriteriaBuilder
                        ->addFilters($enableFilter)
                        ->create();

                        $items = $this->categoryList->getList($searchCriteria)->getItems();

                        if(count($items) == 0)
                        {
                        return FALSE;
                        }

                        foreach ($items as $helpCategory)
                        {
                        $CategoryId = $helpCategory->getId()
                        }
                        return $CategoryId;
                        }





                        share|improve this answer
























                        • +1 For best practice part

                          – Akif
                          Dec 22 '18 at 22:28
















                        2














                        This can be done using service contracts which are considered as best practice.



                        protected $categoryList;

                        /**
                        * @var SearchCriteriaBuilder
                        */
                        protected $searchCriteriaBuilder;

                        /**
                        * @var FilterBuilder
                        */
                        protected $filterBuilder;

                        public function __construct(
                        ------------
                        CategoryListInterface $categoryList,
                        SearchCriteriaBuilder $searchCriteriaBuilder,
                        FilterBuilder $filterBuilder,
                        -----------------
                        )
                        {
                        $this->categoryList = $categoryList;
                        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
                        $this->filterBuilder = $filterBuilder;
                        parent::__construct(----------);
                        }

                        public function getNameCategory()
                        {
                        $enableFilter = $this->filterBuilder
                        ->setField(MagentoCatalogModelCategory::KEY_NAME)
                        ->setConditionType('like')
                        ->setValue(self::CATEGORY_NAME_HELP) // name of the categroy on const
                        ->create();


                        $searchCriteria = $this->searchCriteriaBuilder
                        ->addFilters($enableFilter)
                        ->create();

                        $items = $this->categoryList->getList($searchCriteria)->getItems();

                        if(count($items) == 0)
                        {
                        return FALSE;
                        }

                        foreach ($items as $helpCategory)
                        {
                        $CategoryId = $helpCategory->getId()
                        }
                        return $CategoryId;
                        }





                        share|improve this answer
























                        • +1 For best practice part

                          – Akif
                          Dec 22 '18 at 22:28














                        2












                        2








                        2







                        This can be done using service contracts which are considered as best practice.



                        protected $categoryList;

                        /**
                        * @var SearchCriteriaBuilder
                        */
                        protected $searchCriteriaBuilder;

                        /**
                        * @var FilterBuilder
                        */
                        protected $filterBuilder;

                        public function __construct(
                        ------------
                        CategoryListInterface $categoryList,
                        SearchCriteriaBuilder $searchCriteriaBuilder,
                        FilterBuilder $filterBuilder,
                        -----------------
                        )
                        {
                        $this->categoryList = $categoryList;
                        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
                        $this->filterBuilder = $filterBuilder;
                        parent::__construct(----------);
                        }

                        public function getNameCategory()
                        {
                        $enableFilter = $this->filterBuilder
                        ->setField(MagentoCatalogModelCategory::KEY_NAME)
                        ->setConditionType('like')
                        ->setValue(self::CATEGORY_NAME_HELP) // name of the categroy on const
                        ->create();


                        $searchCriteria = $this->searchCriteriaBuilder
                        ->addFilters($enableFilter)
                        ->create();

                        $items = $this->categoryList->getList($searchCriteria)->getItems();

                        if(count($items) == 0)
                        {
                        return FALSE;
                        }

                        foreach ($items as $helpCategory)
                        {
                        $CategoryId = $helpCategory->getId()
                        }
                        return $CategoryId;
                        }





                        share|improve this answer













                        This can be done using service contracts which are considered as best practice.



                        protected $categoryList;

                        /**
                        * @var SearchCriteriaBuilder
                        */
                        protected $searchCriteriaBuilder;

                        /**
                        * @var FilterBuilder
                        */
                        protected $filterBuilder;

                        public function __construct(
                        ------------
                        CategoryListInterface $categoryList,
                        SearchCriteriaBuilder $searchCriteriaBuilder,
                        FilterBuilder $filterBuilder,
                        -----------------
                        )
                        {
                        $this->categoryList = $categoryList;
                        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
                        $this->filterBuilder = $filterBuilder;
                        parent::__construct(----------);
                        }

                        public function getNameCategory()
                        {
                        $enableFilter = $this->filterBuilder
                        ->setField(MagentoCatalogModelCategory::KEY_NAME)
                        ->setConditionType('like')
                        ->setValue(self::CATEGORY_NAME_HELP) // name of the categroy on const
                        ->create();


                        $searchCriteria = $this->searchCriteriaBuilder
                        ->addFilters($enableFilter)
                        ->create();

                        $items = $this->categoryList->getList($searchCriteria)->getItems();

                        if(count($items) == 0)
                        {
                        return FALSE;
                        }

                        foreach ($items as $helpCategory)
                        {
                        $CategoryId = $helpCategory->getId()
                        }
                        return $CategoryId;
                        }






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jul 12 '18 at 13:04









                        Yogesh AgarwalYogesh Agarwal

                        687315




                        687315













                        • +1 For best practice part

                          – Akif
                          Dec 22 '18 at 22:28



















                        • +1 For best practice part

                          – Akif
                          Dec 22 '18 at 22:28

















                        +1 For best practice part

                        – Akif
                        Dec 22 '18 at 22:28





                        +1 For best practice part

                        – Akif
                        Dec 22 '18 at 22:28











                        1














                        I got it with help from my collage



                        $this->_objectManager->get('MagentoCatalogModelCategoryFactory')->create()->getCollection()
                        ->addFieldToSelect('name')
                        ->addFieldToFilter('name', ['in' => $categoryTitle]);


                        :)
                        Since the collection will only return the record you want you can grab the only result with ->getFirstItem() on the above code






                        share|improve this answer






























                          1














                          I got it with help from my collage



                          $this->_objectManager->get('MagentoCatalogModelCategoryFactory')->create()->getCollection()
                          ->addFieldToSelect('name')
                          ->addFieldToFilter('name', ['in' => $categoryTitle]);


                          :)
                          Since the collection will only return the record you want you can grab the only result with ->getFirstItem() on the above code






                          share|improve this answer




























                            1












                            1








                            1







                            I got it with help from my collage



                            $this->_objectManager->get('MagentoCatalogModelCategoryFactory')->create()->getCollection()
                            ->addFieldToSelect('name')
                            ->addFieldToFilter('name', ['in' => $categoryTitle]);


                            :)
                            Since the collection will only return the record you want you can grab the only result with ->getFirstItem() on the above code






                            share|improve this answer















                            I got it with help from my collage



                            $this->_objectManager->get('MagentoCatalogModelCategoryFactory')->create()->getCollection()
                            ->addFieldToSelect('name')
                            ->addFieldToFilter('name', ['in' => $categoryTitle]);


                            :)
                            Since the collection will only return the record you want you can grab the only result with ->getFirstItem() on the above code







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 12 '16 at 17:31









                            Jacco Amersfoort

                            785717




                            785717










                            answered May 18 '16 at 9:12









                            kiliskilis

                            1491214




                            1491214























                                0














                                To refactor that in a functioning script i suggest using the following



                                $obj = $bootstrap->getObjectManager();
                                $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
                                $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                                if ($collection->getSize()) {
                                $categoryId = $collection->getFirstItem()->getCategoryId();
                                }


                                Edit:
                                I made and tested a script. I created a file in /scripts/file.php



                                <?php
                                use MagentoFrameworkAppBootstrap;
                                require __DIR__ . '/../app/bootstrap.php';

                                $bootstrap = Bootstrap::create(BP, $_SERVER);

                                $obj = $bootstrap->getObjectManager();

                                // Set the state (not sure if this is neccessary)
                                $obj = $bootstrap->getObjectManager();
                                $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
                                $categoryTitle = 'Test';
                                $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);
                                if ($collection->getSize()) {
                                $categoryId = $collection->getFirstItem()->getId();
                                echo $categoryId;
                                }





                                share|improve this answer


























                                • Tried your code , but changed first line to $obj = $this->_objectManager; Got an [MagentoFrameworkExceptionLocalizedException] Invalid attribute name: title error

                                  – kilis
                                  May 12 '16 at 13:36













                                • When you got that error you did not use my script.

                                  – Kay Int Veen
                                  May 12 '16 at 14:04











                                • I just added a fully tested script. please check that. it will work for sure!

                                  – Kay Int Veen
                                  May 12 '16 at 14:09
















                                0














                                To refactor that in a functioning script i suggest using the following



                                $obj = $bootstrap->getObjectManager();
                                $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
                                $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                                if ($collection->getSize()) {
                                $categoryId = $collection->getFirstItem()->getCategoryId();
                                }


                                Edit:
                                I made and tested a script. I created a file in /scripts/file.php



                                <?php
                                use MagentoFrameworkAppBootstrap;
                                require __DIR__ . '/../app/bootstrap.php';

                                $bootstrap = Bootstrap::create(BP, $_SERVER);

                                $obj = $bootstrap->getObjectManager();

                                // Set the state (not sure if this is neccessary)
                                $obj = $bootstrap->getObjectManager();
                                $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
                                $categoryTitle = 'Test';
                                $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);
                                if ($collection->getSize()) {
                                $categoryId = $collection->getFirstItem()->getId();
                                echo $categoryId;
                                }





                                share|improve this answer


























                                • Tried your code , but changed first line to $obj = $this->_objectManager; Got an [MagentoFrameworkExceptionLocalizedException] Invalid attribute name: title error

                                  – kilis
                                  May 12 '16 at 13:36













                                • When you got that error you did not use my script.

                                  – Kay Int Veen
                                  May 12 '16 at 14:04











                                • I just added a fully tested script. please check that. it will work for sure!

                                  – Kay Int Veen
                                  May 12 '16 at 14:09














                                0












                                0








                                0







                                To refactor that in a functioning script i suggest using the following



                                $obj = $bootstrap->getObjectManager();
                                $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
                                $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                                if ($collection->getSize()) {
                                $categoryId = $collection->getFirstItem()->getCategoryId();
                                }


                                Edit:
                                I made and tested a script. I created a file in /scripts/file.php



                                <?php
                                use MagentoFrameworkAppBootstrap;
                                require __DIR__ . '/../app/bootstrap.php';

                                $bootstrap = Bootstrap::create(BP, $_SERVER);

                                $obj = $bootstrap->getObjectManager();

                                // Set the state (not sure if this is neccessary)
                                $obj = $bootstrap->getObjectManager();
                                $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
                                $categoryTitle = 'Test';
                                $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);
                                if ($collection->getSize()) {
                                $categoryId = $collection->getFirstItem()->getId();
                                echo $categoryId;
                                }





                                share|improve this answer















                                To refactor that in a functioning script i suggest using the following



                                $obj = $bootstrap->getObjectManager();
                                $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
                                $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

                                if ($collection->getSize()) {
                                $categoryId = $collection->getFirstItem()->getCategoryId();
                                }


                                Edit:
                                I made and tested a script. I created a file in /scripts/file.php



                                <?php
                                use MagentoFrameworkAppBootstrap;
                                require __DIR__ . '/../app/bootstrap.php';

                                $bootstrap = Bootstrap::create(BP, $_SERVER);

                                $obj = $bootstrap->getObjectManager();

                                // Set the state (not sure if this is neccessary)
                                $obj = $bootstrap->getObjectManager();
                                $_categoryFactory = $obj->get('MagentoCatalogModelCategoryFactory');
                                $categoryTitle = 'Test';
                                $collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);
                                if ($collection->getSize()) {
                                $categoryId = $collection->getFirstItem()->getId();
                                echo $categoryId;
                                }






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited May 12 '16 at 14:05

























                                answered May 12 '16 at 13:29









                                Kay Int VeenKay Int Veen

                                1,0551923




                                1,0551923













                                • Tried your code , but changed first line to $obj = $this->_objectManager; Got an [MagentoFrameworkExceptionLocalizedException] Invalid attribute name: title error

                                  – kilis
                                  May 12 '16 at 13:36













                                • When you got that error you did not use my script.

                                  – Kay Int Veen
                                  May 12 '16 at 14:04











                                • I just added a fully tested script. please check that. it will work for sure!

                                  – Kay Int Veen
                                  May 12 '16 at 14:09



















                                • Tried your code , but changed first line to $obj = $this->_objectManager; Got an [MagentoFrameworkExceptionLocalizedException] Invalid attribute name: title error

                                  – kilis
                                  May 12 '16 at 13:36













                                • When you got that error you did not use my script.

                                  – Kay Int Veen
                                  May 12 '16 at 14:04











                                • I just added a fully tested script. please check that. it will work for sure!

                                  – Kay Int Veen
                                  May 12 '16 at 14:09

















                                Tried your code , but changed first line to $obj = $this->_objectManager; Got an [MagentoFrameworkExceptionLocalizedException] Invalid attribute name: title error

                                – kilis
                                May 12 '16 at 13:36







                                Tried your code , but changed first line to $obj = $this->_objectManager; Got an [MagentoFrameworkExceptionLocalizedException] Invalid attribute name: title error

                                – kilis
                                May 12 '16 at 13:36















                                When you got that error you did not use my script.

                                – Kay Int Veen
                                May 12 '16 at 14:04





                                When you got that error you did not use my script.

                                – Kay Int Veen
                                May 12 '16 at 14:04













                                I just added a fully tested script. please check that. it will work for sure!

                                – Kay Int Veen
                                May 12 '16 at 14:09





                                I just added a fully tested script. please check that. it will work for sure!

                                – Kay Int Veen
                                May 12 '16 at 14:09











                                0














                                I managed to write my own (more efficient) method:



                                $entityTypeId = MagentoCatalogSetupCategorySetup::CATEGORY_ENTITY_TYPE_ID;
                                $row = $this->queryF("SELECT * FROM `eav_attribute` WHERE `entity_type_id` = $entityTypeId AND `attribute_code` = 'name'", 1);
                                $nameAttributeId = $row['attribute_id'];
                                $categoryNames = $this->queryF("SELECT * FROM `catalog_category_entity_varchar` WHERE `attribute_id` = '$nameAttributeId'");
                                $this->categoryNameIdMap = ;
                                foreach ($categoryNames as $item) {
                                $id = $item['entity_id'];
                                $title = $item['value'];
                                $this->categoryNameIdMap[$title] = $id;
                                }


                                This code caches all title:ids into an array, and only query 2 times.



                                Worked for me. Easier to use!






                                share|improve this answer




























                                  0














                                  I managed to write my own (more efficient) method:



                                  $entityTypeId = MagentoCatalogSetupCategorySetup::CATEGORY_ENTITY_TYPE_ID;
                                  $row = $this->queryF("SELECT * FROM `eav_attribute` WHERE `entity_type_id` = $entityTypeId AND `attribute_code` = 'name'", 1);
                                  $nameAttributeId = $row['attribute_id'];
                                  $categoryNames = $this->queryF("SELECT * FROM `catalog_category_entity_varchar` WHERE `attribute_id` = '$nameAttributeId'");
                                  $this->categoryNameIdMap = ;
                                  foreach ($categoryNames as $item) {
                                  $id = $item['entity_id'];
                                  $title = $item['value'];
                                  $this->categoryNameIdMap[$title] = $id;
                                  }


                                  This code caches all title:ids into an array, and only query 2 times.



                                  Worked for me. Easier to use!






                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    I managed to write my own (more efficient) method:



                                    $entityTypeId = MagentoCatalogSetupCategorySetup::CATEGORY_ENTITY_TYPE_ID;
                                    $row = $this->queryF("SELECT * FROM `eav_attribute` WHERE `entity_type_id` = $entityTypeId AND `attribute_code` = 'name'", 1);
                                    $nameAttributeId = $row['attribute_id'];
                                    $categoryNames = $this->queryF("SELECT * FROM `catalog_category_entity_varchar` WHERE `attribute_id` = '$nameAttributeId'");
                                    $this->categoryNameIdMap = ;
                                    foreach ($categoryNames as $item) {
                                    $id = $item['entity_id'];
                                    $title = $item['value'];
                                    $this->categoryNameIdMap[$title] = $id;
                                    }


                                    This code caches all title:ids into an array, and only query 2 times.



                                    Worked for me. Easier to use!






                                    share|improve this answer













                                    I managed to write my own (more efficient) method:



                                    $entityTypeId = MagentoCatalogSetupCategorySetup::CATEGORY_ENTITY_TYPE_ID;
                                    $row = $this->queryF("SELECT * FROM `eav_attribute` WHERE `entity_type_id` = $entityTypeId AND `attribute_code` = 'name'", 1);
                                    $nameAttributeId = $row['attribute_id'];
                                    $categoryNames = $this->queryF("SELECT * FROM `catalog_category_entity_varchar` WHERE `attribute_id` = '$nameAttributeId'");
                                    $this->categoryNameIdMap = ;
                                    foreach ($categoryNames as $item) {
                                    $id = $item['entity_id'];
                                    $title = $item['value'];
                                    $this->categoryNameIdMap[$title] = $id;
                                    }


                                    This code caches all title:ids into an array, and only query 2 times.



                                    Worked for me. Easier to use!







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered 10 mins ago









                                    Mac A.Mac A.

                                    3510




                                    3510






























                                        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%2f115118%2fmagento-2-get-category-id-using-category-title%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

                                        Magento 2 controller redirect on button click in phtml file

                                        Polycentropodidae