以编程方式在magento中创建新类别

时间:2014-01-30 10:17:17

标签: magento

我只想在magento中以编程方式创建新类别。我有一个代码并试过这个但不能成功。

代码在这里: -

<?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);

?>

实际上这个代码的问题每当我尝试它而不是创建新类别但是无法在admin中设置is_active yes。

2 个答案:

答案 0 :(得分:7)

请为该类别设置商店ID。要编写侧magento页面,请使用以下代码:

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);
}

答案 1 :(得分:0)

请参阅我的教程,该教程解释了如何以编程方式创建类别和子类别。

function addManufacturers( $manufacturers ) {
Mage::register('isSecureArea', 1);
$parentId = '2';
$list = array();

foreach ($manufacturers as  $key => $manufacturer) {
    try {

        $enabled = 1;
        if ($key == 0) {
            $parentId = '2';
        }
        else {
            $parentId = $list[0];
        }

        $category = Mage::getModel('catalog/category');
        $category->setName($manufacturer);
        $category->setMetaTitle($manufacturer);
        $category->setIncludeInMenu(1);
        $category->setUrlKey(strtolower($manufacturer));
        $category->setDescription(strip_tags($manufacturer));
        $category->setMetaDescription($manufacturer);
        $category->setMetaKeywords($manufacturer);
        $category->setIsActive($enabled);
        $category->setDisplayMode('PRODUCTS');
        $category->setIsAnchor(1); //for active anchor
        $category->setStoreId(Mage::app()->getStore()->getId());
        $parentCategory = Mage::getModel('catalog/category')->load($parentId);
        $category->setPath($parentCategory->getPath());
        $category->setCustomUseParentSettings(true);
        $category->save();
        $list[$key] = $category->getId();
        echo 'Category ' . $category->getName() . ' ' . $category->getId() . ' imported successfully' . PHP_EOL;
    } catch (Exception $e) {
        echo 'Something failed for category ' . $manufacturer . PHP_EOL;
        print_r($e);
    }
}
return $list;

}

http://www.pearlbells.co.uk/how-to-create-new-categories-and-assigned-products-to-category-programmatically-magento/