Magento how to programmatically create categories


Step 1: Define Function


Magento 1


<?php class MageCheck_Tutorial_IndexController extends Mage_Core_Controller_Front_Action { public function indexAction() { $this-> createCategory(); } public function createCategory() { // ... } }

Magento 2


/** * @var object \Magento\Catalog\Model\Category $category */ protected $_category; public function __construct( \Magento\Catalog\Model\Category $category ){ $this->_category = $category; } public function execute() { $this->creatingCategory(); } public function creatingCategory() { // ... }

Step 2: Create Function


Magento 1


public function createCategory() { $mageFilename = 'app/Mage.php'; $parentId = '2'; // this is id of parent category try { $category = Mage::getModel('catalog/category'); $category->setName('category name'); $category->setUrlKey('category-url-key'); $category->setIsActive(1); $category->setDisplayMode('PRODUCTS'); $category->setIsAnchor(1); $category->setStoreId(Mage::app()->getStore()->getId()); $parentCategory = Mage::getModel('catalog/category')->load($parentId); $category->setPath($parentCategory->getPath()); $category->save(); } catch (Exception $e) { // ... } }

Magento 2


public function creatingCategory() { $category = $this->_category; $category->setName('MageCheck'); $category->setParentId(2); $category->setIsActive(true); $category->setCustomAttributes([ 'description' => 'category example', 'meta_title' => 'category example', 'meta_keywords' => '', 'meta_description' => '', ]); $this->_categoryRepository->save($category); }