How to get category by url key in Magento 2

Sometime during custom development, we need to get category by category key. Recently in one project, I had a task to show category URL key instead of category id on layered navigation. So I need to get category id from url key. So here was my way.

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 = 'tops';

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

OUTPUT:

Array
(
    [0] => Array
        (
            [entity_id] => 367
            [attribute_set_id] => 3
            [parent_id] => 10
            [created_at] => 2020-01-30 21:19:35
            [updated_at] => 2020-07-08 07:48:18
            [path] => 1/2/10/367
            [position] => 2
            [level] => 3
            [children_count] => 0
            [url_key] => tops
        )

    [1] => Array
        (
            [entity_id] => 372
            [attribute_set_id] => 3
            [parent_id] => 9
            [created_at] => 2020-01-30 21:25:46
            [updated_at] => 2020-04-16 00:15:50
            [path] => 1/2/9/372
            [position] => 2
            [level] => 3
            [children_count] => 0
            [url_key] => tops
        )
)

Note that multiple categories may have the same URL keys. So it would 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']);

Hope this article help you to get category by category URL. If you have any questions, feel free to comment below. Thanks for reading.

Keep liking and sharing. Happy Coding 🙂