To support our customers during COVID-19 pandemic, we had introduced many
offers and discounts
to help your ecommerce businesses. Learn more

Magento 2 get category id by category name

Magento 2 get category id by category name

Add 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();
}
January 9, 2018
Did you like this post?
0
0