Magento 2 Get category id using category title
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(
...
\Magento\Catalog\Model\CategoryFactory $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(
...
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $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();
}
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(\Magento\Catalog\Model\Category::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;
}
You can simple do it using name
,
$title = 'womens';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name',$title);
echo "<pre>";
print_r($collection->getData());
exit;