How to create Magento 2 category programmatically?

Use this code:

<?php
use \Magento\Framework\App\Bootstrap;
echo 'code by harshvardhanmalpani';
include('./app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

function createCategory($a='',$b=2,$c=true,$d='',$e='',$f='',$g='') {
        global $objectManager;
        $category = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create();
        $category->setName($a);
        $category->setParentId($b); // 1: root category.
        $category->setIsActive($c);
        $category->setCustomAttributes([
'description' => $d,
'meta_title' => $e,
'meta_keywords' => $f,
 'meta_description' => $g,
     ]);
        $objectManager->get('\Magento\Catalog\Api\CategoryRepositoryInterface')->save($category);
}
createCategory("Abc");
createCategory("Xyz",4,false,"description","m title");
?>

Posted

in

, ,

by

Comments

2 responses to “How to create Magento 2 category programmatically?”

  1. Ioannis Avatar

    Hello, where do we put this code in the bootstarp.php file to add a new category?
    thank you for your reply

    1. Harshvardhan Malpani Avatar

      You can put it any new php file and run it in browser or through cli.

Leave a Reply

Your email address will not be published. Required fields are marked *