VPS business hosting starting at $29.95/24/7 premium technical support

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");
?>

Author: Harshvardhan Malpani

PHP Developer based in New Delhi, India. Working as a freelance web developer providing server deployment, website development and maintenance services.

2 thoughts on “How to create Magento 2 category programmatically?”

Leave a Reply to Harshvardhan Malpani Cancel reply

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