Magento 2 Get category id using category title

The 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.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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();
}

Method 2

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

Edit: The original answer did not show the full paths to the included classes, I had to find the relevant namespaces, so updated the example slightly with a full class and namespaces.

<?php

namespace VendorModuleModelCategories;

use MagentoCatalogApiCategoryListInterface;
use MagentoFrameworkApiSearchCriteriaInterface;
use MagentoFrameworkApiSearchFilterGroup;
use MagentoFrameworkApiFilterBuilder;
use MagentoFrameworkApiSearchSearchCriteriaBuilder;


class CategoriesFilterSearchService
{
    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;
    }

    public function getNameCategory()
    {
        $enableFilter[] = $this->filterBuilder
            ->setField(MagentoCatalogModelCategory::KEY_NAME)
            ->setConditionType('like')
            ->setValue(self::CATEGORY_NAME_HELP) // name of the category 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;
    }
}

Method 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;

Method 4

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();
}

Method 5

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

Method 6

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; 
}

Method 7

First, you need to inject collection factory class

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

After that inside your method, you can do this,

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

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

Method 8

You can use the method loadByAttribute

/** @var MagentoCatalogModelCategoryFactory $this->_categoryFactory */
$category = $this->_categoryFactory->create()->loadByAttribute('name', $name);

Method 9

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!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment