toannk
9/4/2015 - 3:07 AM

magento_create_category.php

<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ToanNK
 * Date: 9/1/15
 * Time: 2:00 PM
 * To change this template use File | Settings | File Templates.
 */
require_once dirname(dirname(dirname(__FILE__))) . '/app/Mage.php';

$app = Mage::app('admin');
//$categoryCollection = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('name',array('eq'=>'Default Category'));
$rootId = 2;

$cat = Mage::getModel('catalog/category')->load($rootId);
$subcats = $cat->getChildren();

foreach(explode(',',$subcats) as $subCatid)
{
    $_category = Mage::getModel('catalog/category')->load($subCatid);
    if($_category->getIsActive()) {
        $sub_cat = Mage::getModel('catalog/category')->load($_category->getId());
        $sub_subcats = $sub_cat->getChildren();
        foreach(explode(',',$sub_subcats) as $sub_subCatid)
        {
            $_sub_category = Mage::getModel('catalog/category')->load($sub_subCatid);
            if($_sub_category->getIsActive()) {
                //echo '<li class="sub_cat"><a href="'.$_sub_category->getURL().'" title="View the products for the "'.$_sub_category->getName().'" category">'.$_sub_category->getName().'</a></li>';
                echo $_sub_category->getName() . PHP_EOL;
            }
        }
    }
}

/* Get new root Id */
$newRootId = 0;
$categoryCollection = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('name',array('eq'=>'Supps Express Root Category'));
if(count($categoryCollection)>0){
    $category = $categoryCollection->getFirstItem();
    $newRootId = $category->getId();
}


function create_new_category($parentId, $name, $urlKey) {
    $category = new Mage_Catalog_Model_Category();
    $category->setName($name);
    $category->setUrlKey($urlKey);
    $category->setIsActive(1);
    $category->setIsAnchor(0);

    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($parentCategory->getPath());

    $category->save();
    unset($category);
}