1

How to create categories programmatically?

0

You can use following code to create category programmatically:

$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');

$cate = $category->getCollection()
            ->addAttributeToFilter('name','test') // replace "test" with your category name.
            ->getFirstItem();

if(!isset($cate->getId())) {
    $category->setPath($parentCategory->getPath())
        ->setParentId($parentId)
        ->setName('test') //replace "test" with your category name.
        ->setIsActive(true);
    $category->save();
}
| improve this answer | |
  • I have tried above but it is not work. – Nilesh Patel Jul 12 '19 at 13:53
  • My code is working fine with attributes, description, price etc but it not importing category. I think the issue with below function. $category->save(); – Nilesh Patel Jul 12 '19 at 13:53
  • @user2710761 Ok let me check it again. – Faisal Sheikh Jul 12 '19 at 14:00
  • @user2710761 I have updated the code please try it, hope it helps you! – Faisal Sheikh Jul 15 '19 at 6:37
  • @user2710761 please don't forget to upvote. – Faisal Sheikh Jul 15 '19 at 9:29

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