How to Create Category Programmatically in Magento 2

categorycategory-attributemagento2

I have one custom table, that table have a column name category which contains the events category like entertainment, national events. Now I need to create category from the table?

note: create category itself enough, don't need to add any products.

I tried with create one category by object manager if the category not exist but it does not work.

    $parentCategory = $this->_objectManager
         ->create('Magento\Catalog\Model\Category')
         ->load('115');
    $category = $this->_objectManager
         ->create('Magento\Catalog\Model\Category');
    $cate=$category->getCollection()->addAttributeToFilter('name',$d["type"])
    ->getFirstItem();
    if(!isset($cate))
    {
    $category->setPath($parentCategory->getPath())
    ->setParentId('115')
    ->setName($d["type"])
    ->setIsActive(true);
    $category->save();
    }

how to deal with automatically create category from table, if not exist already.

Thanks

Best Answer

We need to identify the id of category tree root. Then, we created an instance of the category, set its path, parent_id, name, etc.

/**
 * Id of category tree root
 */
$parentId = \Magento\Catalog\Model\Category::TREE_ROOT_ID;

$parentCategory = $this->_objectManager
                      ->create('Magento\Catalog\Model\Category')
                      ->load($parentId);
$category = $this->_objectManager
                ->create('Magento\Catalog\Model\Category');
//Check exist category
$cate = $category->getCollection()
            ->addAttributeToFilter('name','test')
            ->getFirstItem();

if(!isset($cate->getId())) {
    $category->setPath($parentCategory->getPath())
        ->setParentId($parentId)
        ->setName('test')
        ->setIsActive(true);
    $category->save();
}
Related Topic