4
votes

I try to get a category in Magento 2.0 by it url_key.

Now I've got :

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $categoryFactory = $objectManager->create('Magento\Catalog\Model\CategoryFactory');
        $category = $categoryFactory->create()
            ->addAttributeToFilter('url_key','my_category_url_key');

It returns me this error :

Error filtering template: Invalid method Magento\Catalog\Model\Category\Interceptor::addAttributeToFilter(Array ( [0] => url_key [1] => my_category_url_key ) )

Thanks.

5

5 Answers

4
votes
/**
 * @var \Magento\Catalog\Model\CategoryFactory
 ****** inject in constructor ******
 */
protected $categoryFactory;

---------
---------
---------
$categories = $this->categoryFactory->create()
            ->getCollection()
            ->addAttributeToFilter('url_key','devops')
            ->addAttributeToSelect(['entity_id']);
echo "<pre>";
print_r($categories->getFirstItem()->getEntityId());
2
votes

I know this is an old question, but in case anybody wonders...

All answers here use the ObjectManager. That's bad practice. The correct way to implement this, is as follows:

namespace Vendor\Module\Model;

use Magento\Catalog\Model\CategoryFactory;

class MyClass {

private $categoryFactory;

public function __construct(
    CategoryFactory $categoryFactory
} {
    $this->categoryFactory = $categoryFactory;
}

public function MyFunction() {
    $categoryFactory = $this->categoryFactory->create();
    $category = $categoryFactory->loadByAttribute('url_key', 'my_category_key');
    $categoryId = $category->getId(); // E.g. if you want the ID.
}

This will return the object of the category with URL-key 'my_category_key'.

0
votes

addAttributeToFilter is a method of collections.
You should execute in on a category collection, not on a category instance.

-1
votes

Try this below code, i hope you will get your result.

<?php
$objectManagerr = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManagerr->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categoryy = $categoryFactory->create()
            ->addAttributeToFilter('url_key','your_category_url_key')
            ->addAttributeToSelect('*');

foreach ($categoryy as $productt){

    echo $productt->getName().'<br>';
    echo $productt->getId();
}
?>
-1
votes

Based on your code, you missed the correct method in order to get a category via url_key. Right now we can use method loadByAttribute, so you code should be something like this:

$objectManager   = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->create('Magento\Catalog\Model\CategoryFactory');
$category        = $categoryFactory->create()->loadByAttribute('url_key','my_category_url_key');