cancel
Showing results for 
Search instead for 
Did you mean: 

2.2 get category by url_key

SOLVED

2.2 get category by url_key

Hi,

I need to see if a category exists, I *MUST* (I know it's not the right way, but in this case I'm forced) use object manager and I only have the url_key. How can I do this in magento 2.2?

 

Many thanks

2 REPLIES

Re: 2.2 get category by url_key

Hi @agiorgini,

 

Maybe you can try something like this (I've used a shell class for the PoC).

 

    private $category;

    public function __construct(
         \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        $name = null
    ) {
         $this->category = $categoryFactory;
        parent::__construct($name);
    }

    protected function configure()
    {
        $this->setName('test:category');
        $this->setDescription('Your shell class description.');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $categories = $this->category->create()
            ->getCollection()
            ->addAttributeToFilter('url_key','your-category-url-to-search')
            ->addAttributeToSelect(['entity_id']);
        $output->writeln($categories->getFirstItem()->getEntityId());
    }

And the ouput was the category id.

--
If you've found one of my answers useful, please give "Kudos" or "Accept as Solution"

Re: 2.2 get category by url_key

thanks a lot!