0

我正在使用下面的代码添加一个类别。

我的问题是:如何修改此代码以将类别添加到根类别?

require_once('../app/Mage.php');
Mage::app('mysite');

$category = Mage::getModel('catalog/category');
$category->setStoreId(Mage::app()->getStore()->getId());

if ($id) {
  $category->load($id);
}
$general['name'] = "My Category";
$general['description'] = "Great My Category";
$general['meta_title'] = "My Category"; //Page title
$general['meta_keywords'] = "My , Category";
$general['meta_description'] = "Some description to be found by meta search robots. 2";
$general['is_active'] = 1;
$general['is_anchor'] = 0;
$general['url_key'] = "cars";//url to be used for this category's page by magento.
$category->addData($general);

try {
    $category->save();
    echo "<p>Success! Id: ".$category->getId();
}
catch (Exception $e){
    echo $e->getMessage();
}
4

2 回答 2

1

如果您使用 API 类会更简单:)

try {
    $storeId = Mage::app()->getStore()->getId();
    $parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
    $categoryData = array(
         'is_active'         => TRUE,
         'default_sort_by'   => 'price',
         'available_sort_by' => 'price',
         'include_in_menu'   => TRUE,
         'name'              => 'something here'
    );
    $api = new Mage_Catalog_Model_Category_Api_V2;
    return $api->create($parentId, (object) $categoryData, $storeId);
}
catch(Exception $e) {
    echo $e->getMessage(); // do something here...
}
于 2013-03-01T16:59:22.960 回答
1

只需添加:

$general['path'] = "1/root_id/path_to_your_cat";

使用此路径的路径,例如,如果您要添加的根类别是类别 id 5,请使用:

$general['path'] = "1/5"; 
于 2013-03-01T17:06:57.690 回答