Magento 2 – How to Get Category ID by Category Path

categorymagento2

I have complete category path like Default Category/Men/Sale. How to get category id using it?

Best Answer

Already a similar code is implemented in catalog import module. You can explore the class Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor to learn more about it.

Here is my custom code which gives the category id from fully specified category path Default Category/Men/Sale/Activewear.

<?php

namespace Vendor\Module\Model;

class Category
{
    const DELIMITER_CATEGORY = '/';

    /**
     * Categories id to object cache.
     *
     * @var array
     */
    protected $categoriesCache = [];
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
     */
    private $categoryColFactory;

    /**
     * Category constructor.
     * @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryColFactory
     */
    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryColFactory
    )
    {
        $this->categoryColFactory = $categoryColFactory;
        $this->initCategories();
    }

    public function update() {
            $categoryPath = 'Default Category/Men/Sale/Activewear';
            /** @var string $index */
            $index = $this->standardizeString($categoryPath);
           if (isset($this->categories[$index])) {
               $categoryId = $this->categories[$index]; // here is your category id
               echo $categoryId;
           }
    }

    /**
     * Initialize categories
     *
     * @return $this
     */
    protected function initCategories()
    {
        if (empty($this->categories)) {
            $collection = $this->categoryColFactory->create();
            $collection->addAttributeToSelect('name')
                ->addAttributeToSelect('url_key')
                ->addAttributeToSelect('url_path');
            $collection->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
            /* @var $collection \Magento\Catalog\Model\ResourceModel\Category\Collection */
            foreach ($collection as $category) {
                $structure = explode(self::DELIMITER_CATEGORY, $category->getPath());
                $pathSize = count($structure);
                $this->categoriesCache[$category->getId()] = $category;
                if ($pathSize > 1) {
                    $path = [];
                    for ($i = 1; $i < $pathSize; $i++) {
                        $name = $collection->getItemById((int)$structure[$i])->getName();
                        $path[] = $this->quoteDelimiter($name);
                    }
                    /** @var string $index */
                    $index = $this->standardizeString(
                        implode(self::DELIMITER_CATEGORY, $path)
                    );
                    $this->categories[$index] = $category->getId();
                }
            }
        }
        return $this;
    }
    private function standardizeString($string)
    {
        return mb_strtolower($string);
    }
    private function quoteDelimiter($string)
    {
        return str_replace(self::DELIMITER_CATEGORY, '\\' . self::DELIMITER_CATEGORY, $string);
    }
}
Related Topic