Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create category tree in Magento
<?php
$tree = array(
'Category A' => array(
'Category A-B' => array(
'Category A-B-A',
'Category A-B-B'
),
'Category A-C' => array(
'Category A-C-A',
'Category A-C-B'
),
'Category A-D',
),
'Category B' => array(
'Category B-B' => array(
'Category B-B-A',
'Category B-B-B'
),
'Category B-C' => array(
'Category B-C-A',
'Category B-C-B'
),
)
);
Mage::getModel('namespace_model/setup')->setCategoryTree($tree)->setupCategories();
?>
<?php
class Namespace_Module_Model_Setup extends Mage_Core_Model_Abstract
{
/**
* Category tree for initial setup
*
* @var array
*/
protected $_categories = array();
/**
* Set category tree to create
*
* @param array $tree
* @return Namespace_Module_Model_Setup
*/
public function setCategoryTree($tree)
{
$this->_categories = $tree;
return $this;
}
/**
* Setup categories based on set category tree
*
* @return Namespace_Module_Model_Setup
*/
public function setupCategories()
{
foreach ($this->_categories as $categoryName => $categoryTree) {
$this->_createCategories($categoryName, $categoryTree);
}
return $this;
}
/**
* Create categories recursively
*
* @param string $categoryName
* @param array|null $categoryTree
* @param int $parentId
* @return Namespace_Module_Model_Setup
*/
protected function _createCategories($categoryName, $categoryTree = null, $parentId = 2)
{
$category = Mage::getModel('catalog/category');
$parent = Mage::getModel('catalog/category')->load($parentId);
$category->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
->setName($categoryName)
->setParentId($parentId)
->setPath($parent->getPath())
->setIsActive(1)
->setIsAnchor(1)
->save();
if ($categoryTree && is_array($categoryTree)) {
foreach ($categoryTree as $subCategoryName => $subCategoryTree) {
if (!is_array($subCategoryTree)) {
$subCategoryName = $subCategoryTree;
}
$this->_createCategories($subCategoryName, $subCategoryTree, $category->getId());
}
}
return $this;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.