Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically create new category in magento

Tags:

magento

I just want to create new category programmatically in magento. I have a code and tried this but can't success.

code is here:

<?php
$parentId = '2';

$category = new Mage_Catalog_Model_Category();
$category->setName('check');
$category->setUrlKey('new-category');
$category->setIsActive(1);
$category->setDisplayMode('PRODUCTS');
$category->setIsAnchor(0);

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

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

?>

actually the problem with this code whenever I tried it than it create new category but can't set is_active yes in admin.

like image 838
Ranjeet singh Avatar asked Mar 21 '23 18:03

Ranjeet singh


1 Answers

Please set Store id for that category. To code out side magento page, use codes below:

try{
    $category = Mage::getModel('catalog/category');
    $category->setName('check');
    $category->setUrlKey('new-category');
    $category->setIsActive(1);
    $category->setDisplayMode('PRODUCTS');
    $category->setIsAnchor(1); //for active achor
    $category->setStoreId(Mage::app()->getStore()->getId());
    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($parentCategory->getPath());
    $category->save();
} catch(Exception $e) {
    var_dump($e);
}
like image 86
Amit Bera Avatar answered Apr 08 '23 03:04

Amit Bera