Created
June 24, 2015 09:13
-
-
Save herveguetin/0a377facd130a539dcfe to your computer and use it in GitHub Desktop.
Create category tree in Magento
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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