How to create categories programmatically?


You can use following code to create category programmatically:

$parentId = \Magento\Catalog\Model\Category::TREE_ROOT_ID;

$parentCategory = $this->_objectManager
$category = $this->_objectManager

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

if(!isset($cate->getId())) {
        ->setName('test') //replace "test" with your category name.
  • 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.