How to get category by url key in Magento 2

 

Here is the sample code to get category by category url key.

<?php
namespace Mageprince\Test\Model;
class SampleClass
{
protected $filter;
public function __construct(
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
) {
$this>categoryFactory = $categoryFactory;
}
public function getCategory($urlKey, $parentCatId)
{
$categories = $this>categoryFactory->create()>getCollection()
>addAttributeToFilter(‘url_key’, $urlKey)
>addAttributeToSelect([‘entity_id’]);
return $categories;
}
}

Now you can get category by using function getCategory($urlKey)

$urlKey = ‘cloths’;
$category = $this>getCategory($urlKey);
print_r($category->getData());

Multiple categories may have the same URL keys. So it can be better if you filter the collection by parent category id.

You need to filter category collection by parent_id

$categories = $this>categoryFactory->create()>getCollection()
>addAttributeToFilter(‘parent_id’, 25)
>addAttributeToFilter(‘url_key’, $urlKey)
>addAttributeToSelect([‘entity_id’]);

Share