0

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

0

First WAY 1:

Magento 2 get category id by category name Add the below code to your construct

public function __construct(
    ...
    \Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
    $this->_categoryFactory = $categoryFactory;
    ...
}

Add below code anywhere in class and get category id using category name.

$categoryTitle = 'Men';
$collection = $this->_categoryFactory->create()->getCollection()
              ->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);

if ($collection->getSize()) {
    $categoryId = $collection->getFirstItem()->getId();
}

SECOND WAY 2 :

You can simply do it using category name, by using object manager in any phtml file.

$title = 'womens';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name',$title);
echo "<pre>";
print_r($collection->getData());
exit;

** Happy coding ***

|improve this answer|||||
  • name Sale can be present in root category as well as Default Category/Men/Sale and Default Category/Women/Sale . So above query will not give proper result. – amitshree Mar 22 at 10:35
  • You can add multiple fields to filter ->addFieldToFilter('name','women')->addFieldToFilter('name','sale'); did you try this way ? – Vikas kalal Mar 22 at 10:38
  • But I will not get the exact data. For example Default Category/Women/Sale will have only 1 category id but above code will give me a collection. $collection->getFirstItem()->getId(); will give the first data from collection not exactly the id I am looking for. – amitshree Mar 22 at 10:47
0

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);
    }
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.