Skip to content

Instantly share code, notes, and snippets.

@harshvardhanmalpani
Created October 27, 2017 08:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save harshvardhanmalpani/da17d1a1d87aac0d3a6d76ebb5067203 to your computer and use it in GitHub Desktop.
Save harshvardhanmalpani/da17d1a1d87aac0d3a6d76ebb5067203 to your computer and use it in GitHub Desktop.
How to create Magento 2 category programmatically
<?php
//creating categories in magento 2
//last verified Magento 2.2.0 27 Oct 2017
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");
?>
@kumarbikash411
Copy link

but i am not able to create any category from this , when i run this code it give 500 error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment