Magento create category programmatically

Everyone knows there are admin interface to create categories, but if you want to create a category programmatically. Using Magento’s catalog/category model we can create a Magento category via a program. You have to set category title and Url key in order to show in the frontend. You can create categories programatically in magento. Mage::getModel(‘catalog/category’); is used to initialize and create the category in magento. You can set category url, name, parent category and path etc in the category. Here is simple example of creating category programatically.

public function createCategory(){
    $parentId = 2;// id of parent category 
    $category = Mage::getModel('catalog/category');
    $category->setName('My Category');
    $category->setUrlKey('my-category');
    $category->setIsActive(1); // to make active
    $category->setDisplayMode('PRODUCTS');
    $category->setIsAnchor(1); // This is for active anchor
    $category->setStoreId(Mage::app()->getStore()->getId());
    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($parentCategory->getPath());
    $category->save();
 
}