tuan
9/8/2015 - 12:37 PM

Create list category recursive #Magento #Category #AutoWork

Create list category recursive #Magento #Category #AutoWork

<?php
/**
 * Note that this function do not support:
 *  - Create root category if it is not exits
 *  - The category name must do not duplicate in same root category
 *  - The name of root category must unique
 * @param $arrKey
 * @param $rootCategoryName
 * @throws Exception
 */
$createCategory = function($arrKey, $rootCategoryName) {
    $data = array();
    $arrCategoryObjByName = array();

    // @todo create root category by code so we don't need to throw exception
    $rootCategoryName = trim(stripslashes($rootCategoryName));
    $rootCategoryObj = Mage::getModel('catalog/category')->loadByAttribute('name', $rootCategoryName);
    if(!$rootCategoryObj) {
        throw new Exception("Please create root category name");
    }
    $arrCategoryObjByName[$rootCategoryName] = $rootCategoryObj;


    foreach($arrKey as $strCatHaveParent) {
        $arrCatName = preg_split("#(?<!\\\)/#", $strCatHaveParent);
        $catName = end($arrCatName);
        $catName = stripslashes($catName);

        $data[] = array(
            '_root' => $rootCategoryName,
            '_category' => $strCatHaveParent,
            'description' => $catName,
            'is_active' => 1,
            'include_in_menu' => 1,
            'meta_description' => 'Meta Test',
            'available_sort_by' => 'position',
            'default_sort_by' => 'position',
            'is_anchor' => 1
        );
    }


    foreach($data as $creatorCatData) {
        $category = $creatorCatData['_category'];
        $arrCategory = preg_split("#(?<!\\\)/#", $category);


        for($i =0 ; $i < count($arrCategory); $i++) {

            // Make sure get path of up of it. Make sure create duplicate name if different level
            $categoryObjForGetPath = $rootCategoryObj;
            if($i >= 1) {
                $categoryObjForGetPath = $arrCategoryObjByName[trim(stripslashes($arrCategory[$i-1]))];
            }

            $catName = trim(stripslashes($arrCategory[$i]));
            $category = Mage::getModel('catalog/category')
                ->getCollection()
                ->addAttributeToFilter('name', $catName)
                ->addPathsFilter($categoryObjForGetPath->getPath().'/')
                ->setPageSize(1)
                ->getFirstItem()
                ;
            ;

            // create the category if it not exists
            if(empty($category->getData())) {
                $category = Mage::getModel('catalog/category');

                $_urlKey = $category->formatUrlKey($catName);

                $parentCategoryName = isset($arrCategory[$i-1]) ? $arrCategory[$i-1] : $rootCategoryName;
                $parentCategoryName = trim(stripslashes($parentCategoryName));

                if(!isset($arrCategoryObjByName[$parentCategoryName])) {

                    /* Sure it exists. Because it get before category name */
                    $arrCategoryObjByName[$parentCategoryName] = Mage::getModel('catalog/category')
                        ->getCollection()
                        ->addAttributeToFilter('name', $parentCategoryName)
                        ->addPathsFilter($categoryObjForGetPath->getPath().'/')
                        ->setPageSize(1)
                        ->getFirstItem();

                }

                $parentCategoryObj = $arrCategoryObjByName[$parentCategoryName];

                if(empty($parentCategoryObj->getData())) {
                    throw new Exception(" Cannot get category with name " . $parentCategoryName);
                }

                $dataForCategory = $creatorCatData;
                unset($dataForCategory['_root'], $creatorCatData['_category']);
                $category
                    ->setData(array(
                        $dataForCategory
                    ))
                    ->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
                    ->setName($catName)
                    ->setUrlKey($_urlKey)
                    ->setIsActive(1)
                    ->setIsAnchor(1)
                    ->setPath($parentCategoryObj->getPath())
                    ->save();
            }
            $arrCategoryObjByName[$catName] = $category;
        }
    }
};

$arrKey = array(
    'Notebooks',
    'Notebooks/View all notebooks',
    'Notebooks/Convertibles',
    'Notebooks/Gaming',
    'Notebooks/Performance',
    'Notebooks/Everyday',
    'Notebooks/Everyday',

);
$rootCategory = 'Root';

$createCategory($arrKey, $rootCategory);