1

This question already has an answer here:

I would like to create categories programmatically in magento 2.3

Can you help me to provide us code?

Thanks in advance!

marked as duplicate by Teja Bhagavan Kollepara, Piyush, Rohan Hapani, fmsthird, Muhammad Hasham Jul 15 at 9:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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();
}
  • I have tried above but it is not work. – Nilesh Patel Jul 12 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 at 13:53
  • @user2710761 Ok let me check it again. – Faisal Sheikh Jul 12 at 14:00
  • @user2710761 I have updated the code please try it, hope it helps you! – Faisal Sheikh Jul 15 at 6:37
  • @user2710761 please don't forget to upvote. – Faisal Sheikh Jul 15 at 9:29

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