Magento create Root category programmatically


Magento create Root category programmatically : In magento sometimes we need to create the categories programmatically. The model Mage::getModel(‘catalog/category’); is used for categories in magento. In this tutorial we are going to explain how to create categories programmatically with example.


Magento create Root category programmatically

You can create categories programmatically as below-

Create sub category In Magento –

If you know parent id and want to create the sub category you use the below method –

Magento create category programmatically:

try{
    $category = Mage::getModel('catalog/category');
    $category->setName('Test Category');
    $category->setUrlKey('test-category');
    $category->setIsActive(1);
    $category->setDisplayMode('PRODUCTS');
    $category->setIsAnchor(1); 
	$storeId = Mage::app()->getStore()->getId();
    $category->setStoreId($storeId);
	$parentId = 12;
    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($parentCategory->getPath());
    $category->save();
} catch(Exception $e) {
    echo $e->getMessage();
}

The above example will create a sub category in parent category with $parentId = 12;

Create root category in Magento –

If you want to create root categoory in magento you need to set following two things –

  • Store id as 0
  • Parent Id as 1.

Magento create root category programmatically:

try{
$storeId    = 0;
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
$category->setName('Test category');
$category->setUrlKey('Test category');
$category->setIsActive(1);
$category->setDisplayMode('PRODUCTS');
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
$category->save();
} catch(Exception $e) {
    echo $e->getMessage();
}

The above example will create the root category.


Advertisements

Add Comment

📖 Read More