Magento 2 – get category by url_key
In this short tutorial I show you how to get category by url_key for your Magento 2 shop. This is sometimes needed if your shop already has a category tree and you want to change something programmatically.
Magento 2 – get category by url_key
You can get categories by your categoryFactory. If you want to get categories based on specific attributes, you should do this by filtering a collection. For this you can create a category collection from your categoryFactory on the fly and filter it. You can filter a collection by url_key the exact same way as for all other attributes. The following source code shows you how to do this by url_key filtering:
1 2 3 | $collection = $this->categoryFactory->create() ->getCollection() ->addAttributeToFilter('url_key','main-category') |
If a category with an url-key ‘main-category’ exists, then this collection will consists of this category. Because url_key values are unique, you can either get one or no category (empty collection) in this collection. If you will get more, then you have an error, which results in not savable categories in adminhtml. You will get an error like: “url_key already exists”
Category Factory
The example above uses $this->categoryFactory. You have to inject this into your model like:
1 2 3 4 5 6 7 | public function __construct( ... \Magento\Catalog\Model\CategoryFactory $categoryFactory ) { $this->_categoryFactory = $categoryFactory; ... } |
In __construct() method of your class you have to inject \Magento\Catalog\Model\CategoryFactory so you can use it. If you do, you need to run a setup:di:compile to get it working.
You can also use objectManager to get this model, but I highly recommend not to use this, because of its overhead.
Conclusion
This tutorial showed you how to get category by url_key in Magento 2. url_keys are unique values, so you should only get the expected category. This is useful if you want to progrmmatically want to update categories and all you know about is a sitemap with url_keys.
Was this sample code useful for you? Why do you need to get categories by url_keys?