In today’s blog, we are illustrating how to get a category id by category name in Magento 2.
Call the collection factory in the constructor of the class and using addAttributeToFilter filter the collection by name.
You should make sure your category names are unique, or you have to add the level field in the filter if you have multiple categories in the same name with different levels.
public function __construct(
...........,
..........,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
)
{
$this->_categoryCollectionFactory = $categoryCollectionFactory;
}
public function getCategoryByName() {
$collection = $this->_categoryCollectionFactory->create()
->addAttributeToFilter('name','Men')
->setPageSize(1);
if ($collection->getSize()) {
$categoryId = $collection->getFirstItem()->getId();
}
return $categoryId;
}
Hope this helps to solve your Magento 2 problems.
Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply